Originally Posted by
Codeplug
>> printf("%c\n", (*text)[4]);
That's a bad assumption to make. There's no guarantee that those string literals will be placed back-to-back in memory.
As a matter of fact, there is such a guarantee. This is initialised as an array, and the array elements (the strings, in this case) are guaranteed to be contiguous in memory.
However, a function that receives a raw pointer to pointer to char is not allowed to assume this. For example;
Code:
/* #include appropriate standard headers */
void f(char **x)
{
printf("%c\n", (*x) + 4);
printf("%c\n", x[1][0]);
}
int main()
{
char *text[] = {"foo", "bar"};
char **text2;
/* If your compiler chokes on the following three lines, it is a C++ compiler. A vanilla C compiler will not choke */
text2 = malloc(2*sizeof(char *));
text2[0] = malloc(4);
text2[1] = malloc(4);
strcpy(text2[0], "foo");
strcpy(text2[1], "bar");
f(text);
f(text2);
return 0;
}
The problem, for function f(), is that it cannot assume that the pointer to pointer it is given actually an array of strings, or that elements of that array are contiguous. The first printf() line will generate undefined behaviour when called with f(text2) in the above.