Question

What is printed by the following ANSI C program?

#include<stdio.h>

int main(int argc, char *argv[])
{
       int x = 1, z[2] = {10, 11};
       int *p = NULL;
       p = &x;
       *p = 10;
       p = &z[1];
       *(&z[0] + 1) += 3;
       printf("%d, %d, %d\n", x, z[0], z[1]);
       return 0;
}
Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2022 answer key

Solution

Trace pointer assignments and array modifications step by step.

Step-by-step program trace:

  1. int x = 1, z[2] = {10, 11}; sets x=1x = 1, z[0]=10z[0] = 10, and z[1]=11z[1] = 11.
  2. int *p = NULL; p = &x; makes pp point to variable xx.
  3. *p = 10; assigns the value 10 to xx. Now x=10x = 10.
  4. p = &z[1]; updates pp to point to z[1]z[1].
  5. *(&z[0] + 1) += 3;: Here &z[0] is a pointer to the first element of array zz. Adding 1 moves the pointer to &z[1]. Dereferencing yields the lvalue z[1]z[1]. Adding 3 gives z[1]=11+3=14z[1] = 11 + 3 = 14.
  6. Variable z[0]z[0] is not modified, so z[0]=10z[0] = 10.
  7. printf("%d, %d, %d\n", x, z[0], z[1]); prints 10, 10, 14.
Final answer

Option (D)

Common trap

Overlooking that *(&z[0] + 1) modifies z[1], not z[0].

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

Source

Paper
GATE 2022 Computer Science and Information Technology (CS)
Question
21 of 65
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.