The code snippet is given as:
char *s[] = {"program", "test", "load", "frame", "stack", NULL};
char **p = s + 2;
We need to find the output of following statement:
printf("%s", p[-2] + 3);
What does p[-2] refer to?
char *s[] = {"program","test","load","frame","stack",NULL};
char **p = s + 2
printf("%s", p[-2] + 3);
s is an array of char* pointers.p is a pointer to a pointer. Pointer arithmetics downgrades the array s to a char**, initializing p to a value of two times the size of a char**. On a 32bit machine, if s points to 1000, p will point to 1008.The expression p[-2] is equivalent to *(p - 2), returning a simple pointer to a char*. In this case, a value pointing to the first element of the strings array: "program".
Finally, since *(p - 2) is the expression pointing to the first letter of the string "program", *(p - 2) + 3 points to the fourth letter of that word: "gram".
printf("%s", *(p - 2) + 3); /* prints: gram */
Did you try compiling your code? Once the syntax errors are fixed, the output is gram.
#include <stdio.h>
int main()
{
char *s[] = {"program","test","load","frame","stack",NULL};
char **p = s + 2;
printf("%s",p[-2] + 3);
return 0;
};
See http://ideone.com/eVAUv for the compilation and output.
printf{...);won't compile.{after theprintf. It should be a open parenthesis(, instead. Don't worry - I've fixed it for you.