im trying to wrap my head around a piece of code we got in our C lecture but I can't figure out what it does.
Here's the code:
int main() {
static char *s[] = {"black", "white", "pink", "violet"};
char **ptr[] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
++p;
printf("%s", **p+1);
return 0;
}
The above code prints "ink", but how does it work?
Trying
printf("s: %c\n",*s[0]);
gives me 'b', *s[1] returns 'w', *s[2] returns 'p'and so on. So *s basically returns the first letter of the strings it has been initialized with. Trying
printf("s: %c\n",**ptr[0]);
returns v, so *s seemingly looks like this:
{b,w,p,v};
This, however, is not confirmed by sizeof(s) returning 16 and not 4.
So my question is: whats going on here? Where's the rest of the characters stored?
sand indexi, the expressions[i]is exactly equal to*(s + i). That also means thats + iis exactly equal to&s[i]. And don't forget that arrays naturally decays to pointer to their first elements, i.e.ptrwill decay to&ptr[0]. Those two facts should help explainptrandp. Now, with some pen and paper try to figure out the rest by drawing boxes for each array (and don't forget that the string literals are arrays as well) and using arrows for the pointers.