开发者

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 of char* pointers.
  • The variable 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜