Question

What does the following fragment of C program print?

char c[] = "GATE2011";
char *p = c;
printf("%s", p + p[3] - p[1]);
Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2011 answer key

Solution

Trace the pointer arithmetic and character ASCII differences in C.

  1. The string is "GATE2011". The pointer p points to the start of the string, c[0] ('G').
  1. Evaluate the indices:
  • p[0] = 'G'
  • p[1] = 'A' (ASCII 65)
  • p[2] = 'T'
  • p[3] = 'E' (ASCII 69)
  • p[4] = '2'
  • p[5] = '0'
  • p[6] = '1'
  • p[7] = '1'
  1. Compute the offset:
offset=p[3]−p[1]=’E’−’A’=69−65=4\text{offset} = p[3] - p[1] = \text{'E'} - \text{'A'} = 69 - 65 = 4
  1. The expression p + offset evaluates to p + 4, which points to the character c[4] ('2').
  1. Printing with format string %s prints the null-terminated substring starting at c[4], which is "2011".
Final answer

C

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2011 Computer Science and Information Technology (CS)
Question
22 of 65, printed as CS Q.22
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.