Consider this code:
static char a[2][2] = {
{ 1, 2 },
{ 3, 4 },
};
int main()
{
char **p = (char**)a; // needs cast, or compiler complains (which makes sense)
printf("%p\n", p);
printf("%p\n", &a[1][0]);
printf("%d\n", a[1][0]);
printf("%p\n", &p[1][0]); // why null? why doesn't compiler complain about this?
printf("%d\n", p[1][0]); // segfault, of course
return 0;
}
which yields this output:
0x804a018
0x804a01a
3
(nil)
Segmentation fault
I understand that an array can decay to a pointer. What I don't understand is why the compiler (g++) will let me try to do the reverse. If p is a char**, why does it let me use p[x][x] without so much as a warning? It obviously doesn't even come close to working, as the resulting pointer is null.
Incidentally, I am asking this about code from a 3rd party, which evidently works for them. (compiled in Windows, not with g++). So, I'm not looking for suggestions on how to fix this code, I already know how to do that. I just want to understand why the compiler doesn't complain, and why the result is a null pointer.
Thanks.