IAE Academy

GATE 2025 CS2 Q.62: solution and answer

GATE 2025 · CS2Q.62 · 2 marks · NAT

Consider the following C program:

#include <stdio.h>
int main(){
    int a;
    int arr[5] = {30,50,10};
    int *ptr;
    ptr = &arr[0] + 1;
    a = *ptr;
    (*ptr)++;
    ptr++;
    printf("%d", a + (*ptr) + arr[1]);
    return 0;
}

The output of the above program is __________. (Answer in integer)

See the question in the paper

Answer and solution

ANSWER

The program prints 111.

Official answer: 111Source: Official answer key, GATE 2025 CS2 (IIT Roorkee)

  1. Initialize the array. int arr[5] = {30,50,10}; explicitly sets arr[0]=30, arr[1]=50, arr[2]=10; C zero-fills the remaining elements, so arr[3]=0, arr[4]=0.

  2. Compute the pointer. ptr = &arr[0] + 1; — pointer arithmetic advances by one int per unit (not one byte), so ptr now equals &arr[1], i.e., it points at the element holding 50.

  3. Read through the pointer into a. a = *ptr; copies the current value at that address into a, so a = 50. This is a snapshot: later changes to *ptr do not retroactively change a.

  4. Mutate through the pointer. (*ptr)++; increments the object ptr points to. Since ptr currently aliases arr[1], this changes arr[1] itself, from 50 to 51. (a, already assigned in the previous step, is unaffected.)

  5. Advance the pointer. ptr++; moves ptr to the next int, so it now points at arr[2], whose value is 10 (never modified).

  6. Evaluate the printf arguments. At this point: a = 50, *ptr = arr[2] = 10, arr[1] = 51 (post-increment). So the expression a + (*ptr) + arr[1] = 50 + 10 + 51.

  7. Sum and print. 50 + 10 + 51 = 111. The program prints 111.

KEY IDEA

Partial array initializers zero-fill the remaining elements; pointer arithmetic (&arr[0] + 1) moves by one element's width, not one byte; and *ptr and arr[1] refer to the same memory once ptr points into arr[1], so a change through one is visible through the other.

WATCH OUT FOR

Treating a, *ptr, and arr[1] as three independent values once (*ptr)++ fires, instead of recognizing ptr aliases arr[1] at that point (so the increment changes arr[1] itself) — or forgetting that a already captured the old value of 50 before the increment happened, and wrongly using the post-increment value for a too.

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

More Pointers & arrays questions