Reputation: 13
I'm trying to do something like this:
int main()
{
char strMat[][32] = { {"FIRST"}, {"SECOND"}, };
printf ("%s\n", strMat[0]);
test ((char **) strMat);
return 0;
}
void test (char **strMat)
{
printf ("%s\n", strMat[0]);
}
I haven't been able to figure out why before calling test() the first string is written properly, but later I get a segmentation fault. In other sections of code I call test() with argv and it works fine. Why trying to print strMat[0] on the test function results in a segmentation fault?
Upvotes: 1
Views: 48
Reputation: 133609
A char[2][32]
is not a char**
but a contiguous block of 2*32 bytes of memory. This can be highlighted by printing the pointers:
printf("%p %p %p\n", strMat[0], &strMat[0], &strMat[1]);
When you coerce the type to a char**
you interpret the data contained in the array as memory addresses which unavoidably refer to invalid memory.
Indeed if you try to print the invalid address that you assume is correct, eg:
printf("%p\n", ((char**)strMat)[0]);
You get 0x5453524946
, which, interpreted as an array of bytes like 0x54 0x53 0x52 0x49 0x46
, yields 'T' 'S' 'R' 'I' 'F'
which shows the issue (the characters are reversed because I'm assuming a little endian platform).
Upvotes: 2