What does the following fragment of C program print? char c[] = " GATE2011";…

2011

What does the following fragment of C program print?

char c[] = " GATE2011";
char *p = c;
printf("%s", p + p[3] - p[1]);

  1. A.

    GATE2011

  2. B.

    E2011

  3. C.

    2011

  4. D.

    011

Attempted by 189 students.

Show answer & explanation

Correct answer: C

Answer: 2011

  1. Write the string with indices: c = "G A T E 2 0 1 1 \0". Indices: 0:'G', 1:'A', 2:'T', 3:'E', 4:'2', 5:'0', 6:'1', 7:'1', 8:'\0'.

  2. Find the character values used in the arithmetic: p[3] is 'E' and p[1] is 'A'.

  3. Compute the difference: p[3] - p[1] = 'E' - 'A' = 69 - 65 = 4.

  4. Advance the pointer by that difference: p + (p[3] - p[1]) = p + 4, which points to index 4 (the character '2').

  5. printf("%s", p + 4) prints the substring starting at index 4: "2011".

Final output: 2011

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir