Question

Consider the following C program.

#include <stdio.h>
int main() {
    int a[4][5] = {{
        {1, 2, 3, 4, 5},
        {6, 7, 8, 9, 10},
        {11, 12, 13, 14, 15},
        {16, 17, 18, 19, 20}
    }};
    printf("%d\n", *(*(a + **a + 2) + 3));
    return (0);
}

The output of the program is _______.

Official answer and solution
Official answer
19
From
Official GATE 2020 answer key

Solution

Evaluate pointer dereferences and array subscript offsets step by step.

Given array declaration: int a[4][5] = {{1..5}, {6..10}, {11..15}, {16..20}};.

Step 1: Evaluate **a:

  • a decays to a pointer to its first row a[0] (type int (*)[5]).
  • *a is the array a[0], which decays to a pointer to its first element &a[0][0] (type int *).
  • **a = *(*a) = a[0][0] = 1.

Step 2: Evaluate a + **a + 2:

  • a + 1 + 2 = a + 3.
  • a + 3 points to the 4th row of the 2D array, which is a[3].

Step 3: Evaluate *(*(a + 3) + 3):

  • *(a + 3) is the array a[3], which decays to &a[3][0].
  • Adding 3 gives &a[3][3].
  • Dereferencing *(&a[3][3]) gives a[3][3].
  • The 4th row a[3] contains {16, 17, 18, 19, 20}.
  • Index 0 is 16, index 1 is 17, index 2 is 18, and index 3 is 19.
  • Thus, the printed output is 19.
Final answer

19

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

Source

Paper
GATE 2020 Computer Science and Information Technology (CS)
Question
32 of 65, printed as CS Q.22
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.