Reputation: 771
Here is what I'm trying:
int a,b;
int *ptr;
a = 123;
ptr = &a;
b = *ptr;
printf("&a is %p\n",&a);
printf("ptr points to %p\n",ptr);
printf("&ptr is %p\n",&ptr);
printf("&b is %p\n",&b);
Results in:
&a is 0x7ffee01fc828
ptr points to 0x7ffee01fc828
&ptr is 0x7ffee01fc818
&b is 0x7ffee01fc820
I expected &b to show the same address as &a... But that's not the case, so I tried:
int a,*b;
int *ptr;
a = 123;
ptr = &a;
b = ptr;
printf("&a is %p\n",&a);
printf("ptr points to %p\n",ptr);
printf("&ptr is %p\n",&ptr);
printf("&b is %p\n",&b);
This still results in an unexpected memory address for &b:
&a is 0x7ffee1cbd828
ptr points to 0x7ffee1cbd828
&ptr is 0x7ffee1cbd818
&b is 0x7ffee1cbd820
Can someone help me understand why I'm unable to get &b matching the same address as &ptr or &a?
Thanks!
Upvotes: 3
Views: 573
Reputation: 162164
I expected &b to show the same address as &a…
Having that expectation means, that you have a wrong mental model about how pointers work and what their semantics are in the C programming language. The key misconception seems to happen at these two lines of the original code fragment:
First you have
b = *ptr;
This line translates into *"copy the contents of the memory at address ptr
into the variable b
." The variable b
never even gets into contact with the pointer itself. You could rewrite it perfectly fine to the same effect into
int tmp = *ptr;
b = tmp;
As a matter of fact, every modern C compiler out there will produce identical code for either case.
The second line where you have a misconception is this one
printf("&b is %p\n",&b);
specifically the effects of taking the address of the variable b
, i.e. the result of &b
. b
is a completely independent variable, with its very own address. This address cannot be changed! The only thing that can be changed about a variable is its value.
Pointers are variables, too, and yes, a pointer does have an address itself. The value of a pointer is the address it points to. But like every variable, you cannot change the address where the variable is stored and when you assign an address to a pointer, you are changing its value. Hence when in your second code snipped you assign b = ptr;
you're copying the value of ptr
to b
. After that, both ptr
and b
point to the same address, but these two pointers are two independent copies of the same value, where each copy is placed at a different place in memory. Naturally taking the address of b
yields something different as the address of ptr
.
Upvotes: 3
Reputation: 140168
now a
,b
and ptr
are 3 different variables (regardless of their type)
So their address is different. You'll have the same values by not taking the address of pointer variables.
int a,*b;
int *ptr;
a = 123;
ptr = &a;
b = ptr;
printf("&a is %p\n",&a);
printf("ptr points to %p\n",ptr);
printf("b is %p\n",b);
Upvotes: 3