Thursday, August 6, 2009

Cool query 'bout pointers

While studying 'bout pointers I came about a cool phenomenon. Plzz don't laugh if its a but obvious thing for you. You might be a better coder than me for sure. I figured it out after a number of trials so I can't stop myself sharing it with everyone.

My question is.. Whats the difference between two statements..
int a=1;
int *p;
*p=a;//statement 1

AND

int a=1;
int *p;
p=&a;//statement 2

I played with number of printf's to come out with a simple answer. I again warn you if its a but obvious thing plzz do ignore it but it was a beautiful discovery for me though.

p=&a : in this statement, as we all know, the address of variable 'a' gets stored in pointer p and we say that pointer p points towards the variable a.

*p=a : (value of p is equal to a) in this statement, "as now I know", a new address is designated as value 1 and the pointer points to that address rather than pointing towards a. In simple words the address stored in p is not the address of a.

try two statements with..
printf("%u" "%u",p,&a);
In first you will find same address and different in the second.

* * * * *

No comments:

Post a Comment