I am a begineer in C and I am trying to understand pointer to pointer concept. I have the following example
int main() {
char *names[]={"Peter", "Dan"};
printf("names = %p\n", names);
printf("(char *)names = %p\n", (char *)names);
printf("(char **)names = %p\n", (char **)names);
printf("*(char *)names = %p\n", *(char *)names);
printf("*(char **)names = %p\n", *(char **)names);
return 0;
}
Output:
names = 0x7fff167f7c00
(char *)names = 0x7fff167f7c00
(char **)names = 0x7fff167f7c00
*(char *)names = 0x58
*(char **)names = 0x400658
Here my question why *(char *)names doesn't return me the 0x400658 ? From the above output i can see that value of (char *)names is 0x7fff167f7c00, now if i dereference this it should show me 0x400658 right ?
Could someone please explain me how this works ?
EDITED after the initial question:
I did some further analysis and figured out some theory but still need help to understand. When doing (char *)names, it thinks that it is pointer to char hence *(char *)names prints 1 byte of the address of 0x400658 i.e. 0x58. But in (char **)names case it thinks that as pointer to pointer and when dereferencing that it gives the whole address i.e.0x400658. Below will help newbies like me to understand this more
printf("notes =%p\n", notes);
printf("(char *)notes+1 =%p\n", ((char *)notes+1));
printf("(char **)notes+1 =%p\n", ((char **)notes+1));
Output:
notes =0x7fff75e4c260
(char *)notes+1 =0x7fff75e4c261
(char **)notes+1 =0x7fff75e4c268
Above was my theory but now lets say what i observed is correct but sometimes am getting below output
*(char **)notes =0x4007ec
*(char *)notes =0xffffffec
here this should be 0xec considering my theory is correct ? why is it appended by ffff ? Am i missing something here ?
char *and dereferencing . Search "strict aliasing rule" to get full list of allowed combinations (also allow for alignment).