Question

Consider the following C program.

#include <stdio.h>
int main()
{
    static int a[] = {10, 20, 30, 40, 50};
    static int *p[] = {a, a + 3, a + 4, a + 1, a + 2};
    int **ptr = p;
    ptr++;
    printf("%d%d", ptr - p, **ptr);
}

The output of the program is _____.

Official answer and solution
Official answer
140
From
Official GATE 2015 answer key

Solution

Trace pointer initialization, pointer arithmetic, and indirection step-by-step.

Analyze the arrays:

  1. a = {10, 20, 30, 40, 50} has base address &a[0]:
    • a points to a[0] = 10
    • a + 1 points to a[1] = 20
    • a + 2 points to a[2] = 30
    • a + 3 points to a[3] = 40
    • a + 4 points to a[4] = 50
  1. p = {a, a + 3, a + 4, a + 1, a + 2} is an array of pointers to int:
    • p[0] = &a[0]
    • p[1] = &a[3]
    • p[2] = &a[4]
    • p[3] = &a[1]
    • p[4] = &a[2]
  1. int **ptr = p; initializes ptr to &p[0].
  2. ptr++; advances ptr by one element, so ptr now points to p[1].
  3. Compute expressions in printf("%d%d", ptr - p, **ptr):
    • ptr - p: pointer subtraction between &p[1] and &p[0] evaluates to the index difference, which is 11.
    • *ptr evaluates to p[1], which is a + 3 (pointing to a[3]).
    • **ptr evaluates to *(a + 3) = a[3] = 40.

The format string "%d%d" outputs 1 immediately followed by 40, resulting in 140.

Final answer

140

Common trap

Inserting an unintended space between the two values, or confusing pointer difference ptr - p (which is in units of sizeof(*p), yielding 1) with byte offset.

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

Source

Paper
GATE 2015 Computer Science and Information Technology (CS) Session 3
Question
36 of 65, printed as CS Q.26
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.