I’m sure this has been asked before, but a cursory google and stack overflow search didn’t turn up the answer.
#include <stdio.h>
int main() {
char a[128][1024];
strcpy(a[0], "hello");
strcpy(a[1], "foo");
strcpy(a[2], "bar");
char **b = a;
printf("%s\n", a[0]); //same as printf("%s\n", a)
printf("%s\n", a[2]+1); //print from 2nd char of 3rd string
printf("%s\n", b); //same as printf("%s\n", a), makes sense
printf("%s\n", b[0]); //segfault???
}
First off, why is the last one a segfault? I’d expect same behavior as array a. How would I access the n-th string from b in a generalized way? What are the differences in treatment between a and b?
On a similar note, the way I understand it, a[n] is syntactic sugar for *(a+n). Is this correct, both for pointers and for arrays? Yet it seems getting different behavior for a and b.
Thanks!
char **bsays “At the place wherebpoints,b[0], there is a pointer to a char. And, if I useb[1],b[2],…, those are also pointers to char.”In contrast
char a[128][1024]says “ais 128 arrays of 1024 char.” When you do this, at the place whereais, there are no pointers. There are just char. In memory, it looks like 131,072 char in a row (128•1024 = 131,072).When you assign
char **b = a, assuming the compiler allows you to, you setbto be the address ofa. When you useb[0], there should be a pointer there. But there is not. There are just char there. When you passb[0]to printf, the compiler goes to wherebpoints, loads several bytes as if they were a pointer, and passes the resulting value to printf. Then printf crashes, because the bytes point to some bad location.A proper definition of
bwould bechar (*b)[1024] = a;.