# Pointers and dynamic memory: GATE CS question with solution

From the GATE Daily set of 27 October 2026, question 5 of 10 (https://gatedaily.in/q/2026-10-27-pointer-difference-assigned-to-array/). Difficulty: standard.

### Q.5 · Programming & Data Structures · Pointers and dynamic memory · MCQ, 1 mark (choose one option)

Assume `int` is 4 bytes. What does the following C program print?

```c
#include <stdio.h>
int main(void) {
    int a[6] = {4, 9, 2, 7};
    int *p = a + 3;
    int *q = &a[1];
    *q += *p;
    p--;
    *p = p - q;
    printf("%d %d %d", a[1], a[2], *(q + 3));
    return 0;
}
```

(A) 16 1 0
(B) 16 4 0
(C) 16 1 7
(D) 11 1 0

**Answer:** (A) 16 1 0

**Solution.** **Method.** Lay the array out with indices and follow each pointer as an index.

| index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| start | 4 | 9 | 2 | 7 | 0 | 0 |

The initialiser lists four values, so `a[4]` and `a[5]` are 0.

- `p = a + 3` points to index 3; `q = &a[1]` points to index 1.
- `*q += *p`: `a[1] = 9 + 7 = 16`.
- `p--`: `p` now points to index 2.
- `*p = p - q`: the difference of two `int *` is the number of elements between them, $2 - 1 = 1$, so `a[2] = 1`.
- `*(q + 3)` is index $1 + 3 = 4$, which holds 0.

Output: `16 1 0`.

**The trap.** Pointer subtraction is scaled by the element size, so it gives 1 here, not 4 bytes; the "`int` is 4 bytes" line is there to tempt exactly that slip. Also, `q + 3` is relative to `q` (index 1), not to the start of the array.

**What was tested.** Pointer arithmetic in units of elements, the difference between writing through a pointer (`*q += ...`) and moving it (`p--`), and zero-filling of a partially initialised array.

**Remember:** Pointer arithmetic counts elements: p + k moves k elements and p - q gives the number of elements between them, whatever the element size. Convert every pointer to an array index and the trace becomes simple.

**Why each option:**
- (A) A[1] becomes 9 + 7, a[2] gets the element distance 1, and q + 3 points to a[4], which the initialiser zero-filled.
- (B) Treats p - q as a byte distance (1 int = 4 bytes); pointer subtraction counts elements, not bytes.
- (C) Reads *(q + 3) as a[3]; q points to a[1], so q + 3 is a[4], which is 0.
- (D) Takes a + 3 as pointing to a[2] (value 2); a + 3 is &a[3], whose value is 7.
