Tuesday, July 14, 2009

About pointers in C...?

i am confused between these two..





int *s,p=1;





s=%26amp;p;


s=p;





if s=%26amp;p points the address of p by s


how about s=p?


what is the difference between the two?

About pointers in C...?
s=%26amp;p


means you are assigning the address of the variable 'p' to the pointer variable 's'


and i think the second statement "s=p" will generate an error... coz you are trying to assign an int value to an int pointer.
Reply:So, think of a computer's memory as a long tape, and an address as a position on that tape. A pointer is simply an address contained in a variable that tells the computer to go to the position on the tape that's specified in the variable, got it? Now, by going %26amp;p, you're looking for where p is on that 'tape' so the computer can find it and change it's value later. When you store p into s, you're storing the contents of p into something that's supposed to only hold an address. So, when the computer tries to dereference the pointer, it ends up looking for this value that could be anywhere on the 'tape', but doesn't refer to anything specifically, which is very bad. The only time you'd see something like s=p is if both were pointers, and you want p to refer to whatever s was referring to in the first place.
Reply:s = p will store what's in p into s, in other words s will contain 1. This is of course NOT what s is meant to have in it, and any decent C compiler should produce at least a warning message about this


No comments:

Post a Comment