Saturday, March 13, 2010

pointer operation with &,*

int main()
{
int *p;
int a=2;
p=&a;
printf("%d",&p); //prints the address of p.
printf("%d",*(&p));//prints the address of a.
printf("%d",*(*(&p));//prints the value a.
printf("%d",&a); //prints the address of a.
printf("%d",*(&a));// prints the value of a.

return 0;
}

Logic:
& operator specifies the address of the variable.
* operator specifies the value at the address. ( *(1000) gives the value at the address 1000).

For this program:
assume address of p is 1000 and a is 1002.
&p will print the 1000 in output screen.
*(&p) is equal to *(1000) . This will give the value at address 1000(i.e address of a because p stores the address of a) .so now *(&p) is equal to 1002(address of a).

*( *(&p) ) is equal to *(1002) . so this will give the value at the address 1002. i.e.,2


&a results the address of a.
*(&a) results the value at address .so results the value of a.

0 comments:

Post a Comment