This blog is under construction

Saturday, 5 October 2013

Difference between asterisk and ampersand operators in c

Address Operator (& - Ampersand):
Returns address of the given variable.  Consider the following example,
int *ptr, var = 10;
ptr = &var;

ptr = &var sets the address of the variable var to pointer ptr.  & is also called as reference operator.

Let us try to understand the purpose of reference operator using the following example program.


  #include <stdio.h>
  int main() {
        int var = 10, *ptr;

        /* assigning address of variable var to pointer ptr */
        ptr = &var;
        /* printing the address of the variable var */
        printf("Address of var is 0x%x\n", &var);
        /* printing the value of pointer ptr */
        printf("Value of ptr is 0x%x\n", ptr);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Address of var is 0xbfdf202c
  Value of ptr is 0xbfdf202c



Indirection Operator('*' - asterisk):
The dereference operator is an unary operator which returns the value of the pointee by dereferencing the value(address) in pointer variable.  Consider the following example,

int var1 = 10, var2;
int *ptr;   // '*' used for declaration
ptr = &var;
var2 = * ptr;  //'*' used for deferencing

The above statement(var2 = *ptr) dereferences the address in ptr and assigns the pointee value(value of var1) to var2.  Now, the value of var2 becomes 10.  * is also called as dereference operator.

Let us try to understand the purpose of dereference operator using the following example program.


  #include <stdio.h>
  int main() {
        int var1 = 10, var2;
        int *ptr;
        /* assigning the address of variable var1 to pointer ptr */
        ptr = &var1;
        /* assigning dereferenced value to var2 */
        var2 = *ptr;

        /* printing addresses and values of the variables */
        printf("Address of var1 is 0x%x\n", &var1);
        printf("Address of var2 is 0x%x\n", &var2);
        printf("Value of ptr is 0x%x\n", ptr);
        printf("Value of var1 is %d\n", var1);
        printf("Value of *ptr is %d\n", *ptr);
        printf("Value of var2 is %d\n", var2);
        return 0;
  } 




  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Address of var1 is 0xbff7c72c
  Address of var2 is 0xbff7c728
  Value of ptr is 0xbff7c72c
  Value of var1 is 10
  Value of *ptr is 10
  Value of var2 is 10


1 comment: