Question
What does the following fragment of C program print?
char c[] = "GATE2011";
char *p = c;
printf("%s", p + p[3] - p[1]);Official answer and solution
- Official answer
- C
- From
- Official GATE 2011 answer key
Solution
Trace the pointer arithmetic and character ASCII differences in C.
- The string is
"GATE2011". The pointerppoints to the start of the string,c[0]('G').
- 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'
- Compute the offset:
- The expression
p + offsetevaluates top + 4, which points to the characterc[4]('2').
- Printing with format string
%sprints the null-terminated substring starting atc[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.