1

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?

2
  • 2
    There is a syntax error: printf{...); won't compile. Commented Feb 14, 2011 at 12:11
  • As @vz0 says, there's a curly brace { after the printf. It should be a open parenthesis (, instead. Don't worry - I've fixed it for you. Commented Sep 6, 2011 at 0:26

2 Answers 2

2
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 */
Sign up to request clarification or add additional context in comments.

1 Comment

Aren't negative array indexes UB?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.