So I am trying to figure out pointers and I read some posts on pointers to pointers but I can't still figure out why this program runs without trouble
#include <stdio.h>
#include <assert.h>
int main(){
char* p = "abc";
char** pp[2];
pp[0] = &p;
assert(*pp[0]==**pp);
printf("Comparison: %s, %s\n",**pp, *pp[0]);
return 0;
}
As far as I understand now the memory would look something like this
Memory Address (hex) Variable name Contents
1000 'a' == 97 (ASCII)
1001 'b' == 98
1002 'c' == 99
1003 0
...
2000-2003 p 1000 hex
...
3000-3003 pp[0] 2000 hex
At this point assuming that I got the memory thing right... I would expect *pp[0] to go into memory and say...
So pp[0] points to the address of p, which is 0x2000, and by dereferencing I would expect to get the contents of address 0x2000 which in my point of view means that I would get the 0x1000 but that is not the case since the output of the program is:
OUTPUT
abc, abc
In the case of **pp I think it first dereferences pp which will give us the contents of whatever pp is pointing to, that means the contents of 0x2000 (which is 0x1000) and then by dereferencing again we get the contents of address 0x1000
Why would they be equal? Where am I missing something
In most contexts, if you have an array a, then a is short for &a[0]. (There are some exceptions, such as with sizeof a or &a).
So **pp really means **&pp[0].
&pp[0] is the address of pp[0], so *&pp[0] is equivalent to just pp[0], so **&pp[0] is equivalent to *pp[0].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With