GATE / CS ARCHIVE

GATE CSE 2011 / QUESTION 22

Pointer arithmetic in string output

Programming in C · Pointers & Memory · Full GATE CSE 2011 paper

GATE 2011, Q22 1 mark · MCQ
Report issue

Pointers & Memory

Question 22, GATE 2011: What does this literal C fragment print? The initial capital in Char is as printed.
Char c[] = "GATE2011";
char *p = c;
printf("%s", p + p[3] - p[1]);

(A) GATE2011
(B) E2011
(C) 2011
(D) 011
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C only under intended offset arithmetic; literal C is not well-defined

Using ASCII arithmetic, E−A=4, so the intended pointer is c+4 and the intended suffix is 2011, C. But p+p[3]−p[1] associates as (p+p[3])−p[1]. Its first pointer operation forms p+69 in ASCII, far beyond the 9-byte array, causing undefined behavior before the subtraction returns to offset 4. The source also capitalizes Char, which is not the C keyword char unless separately defined. Replacing Char with char and writing p+(p[3]−p[1]) repairs the intended calculation, still with an explicit character-encoding assumption. The official result is not a guarantee of the literal fragment.

Index the intended string: c[0]='G', c[1]='A', c[2]='T', c[3]='E', c[4]='2', c[5]='0', c[6]='1', c[7]='1', c[8]='\0'. A valid pointer to c[4] makes %s print characters until c[8], producing 2011. This explains the examiner's arithmetic but must not erase the separate language-law issues in the literal source. Pointer arithmetic has validity requirements at every intermediate operation, not only at the final address.

Original paper, page 5 · Answer key