GATE / CS ARCHIVE

GATE CSE 2017 SET 2 / QUESTION 55

GATE CSE 2017 Set 2 Q55

Programming in C · Pointers & Memory · Full GATE CSE 2017 Set 2 paper

GATE 2017 Set 2, Q55 2 marks · NAT
Report issue

Pointers & Memory

Question 55, GATE 2017: C program includes stdio.h and string.h, then executes char *c="GATECSIT2017"; char *p=c; printf("%d",(int)strlen(c+2[p]-6[p]-1));. What output is intended, and what caveat applies to the printed expression?
Tap to enlarge
Answer & solution

Official answer: 2.0

Our answer: 2 under intended character-offset arithmetic; strict C undefined behavior

1. C defines a[b] as *(a+b), so 2[p]=p[2] and 6[p]=p[6]. In the string, these are T and I. Under ASCII-compatible character values, T-I-1=84-73-1=10.

2. If this integer offset is computed before pointer addition, c+10 points to the suffix "17" of GATECSIT2017. strlen then returns 2, and the explicit cast to int matches the %d format. This explains the official intended numerical answer.

3. Strictly, however, the printed additive expression is left-associative: ((c+2[p])-6[p])-1. Its first addition forms c+84, far outside the string object (12 characters plus its terminator). C does not allow that intermediate out-of-bounds pointer arithmetic, even if later subtraction would return to a valid offset. The printed program therefore has undefined behavior rather than a guaranteed output.

4. Writing c+(2[p]-6[p]-1) would avoid that intermediate-pointer problem under the intended encoding. The answer 2 additionally assumes an encoding giving the specified T-I difference; C does not require alphabetic characters to have ASCII codes. Preserve both the official intended answer and the strict-C/encoding caveat.

Original paper, page 22 · Answer key