Character array and pointer
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);
- The variable
s
is an array ofchar*
pointers. - The variable
p
is a pointer to a pointer. Pointer arithmetics downgrades the arrays
to achar**
, initializingp
to a value of two times the size of achar**
. On a 32bit machine, ifs
points to1000
,p
will point to1008
.
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.
精彩评论