GATE Daily

Tuesday27 October 2026

Past sets27 Oct 2026DS

Pointers and dynamic memory: GATE CS question with solution

Q.5

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

#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;
}
One try. It counts in your 27 Oct 2026 set.
Show solution
RememberPointer 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.

Solution MCQ · 1 mark · −⅓ if wrong

Answer: (A) 16 1 0

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, , so a[2] = 1.
  • *(q + 3) is index , 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.

Copied. Paste it into the new chat.Too long to send. Copy the question and solution by hand.