IAE Academy

GATE 2022 CS Q.21: solution and answer

GATE 2022 · CSQ.21 · 1 mark · MCQ

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;
}
  1. (A)

    1, 10, 11

  2. (B)

    1, 10, 14

  3. (C)

    10, 14, 11

  4. (D)

    10, 10, 14

See the question in the paper

Answer and solution

ANSWER

The program prints 10, 10, 14 — option (D).

Official answer: DSource: Official answer key, GATE 2022 CS (IIT Kharagpur)

  1. Initialization: x = 1; z[0] = 10, z[1] = 11 (array-initializer order).

  2. p = &x; then *p = 10; writes through p into x, so x becomes 10. z[0] and z[1] are unaffected.

  3. p = &z[1]; only changes what p points to — no dereference occurs, so no memory value changes at this line.

  4. (&z[0] + 1) += 3; — &z[0] is int, so &z[0] + 1 is the address of the next int in the array, which (by contiguity of array storage) is exactly &z[1]. This step is independent of the current value of p. It reads z[1] = 11, adds 3, and stores z[1] = 14.

  5. Final values: x = 10, z[0] = 10 (never modified after initialization), z[1] = 14.

  6. printf("%d, %d, %d\n", x, z[0], z[1]) prints: 10, 10, 14 — option (D).

KEY IDEA

A pointer variable only affects memory when it is dereferenced; assigning a new address to p does nothing by itself. The expression *(&z[0] + 1) uses pointer arithmetic directly (array-to-pointer decay plus offset) and is completely independent of whatever p currently holds — it always denotes z[1] here regardless of the intervening p = &z[1]; line.

WATCH OUT FOR

Assuming that because p was just set to &z[1], the very next statement *(&z[0] + 1) += 3; must be "using p" or must somehow interact with it, and then either double-adding through p or getting confused about which variable receives the += 3. In fact p is a red herring for this line: &z[0] + 1 is computed independently as the address of z[1], so the update is simply z[1] = 11 + 3 = 14.

From the GATE 2022 CS paper. Every question of this paper · Download the full paper · All 11 Pointers & arrays questions, with notes

More Pointers & arrays questions