IAE Academy

GATE 2020 CS Q.22: solution and answer

GATE 2020 · CSQ.22 · 1 mark · NAT

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 ____________.

See the question in the paper

Answer and solution

ANSWER

The output of the program is 19.

Official answer: 19Source: Official answer key, GATE 2020 CS (IIT Delhi)

  1. a is declared as int a[4][5] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20}}.

  2. *a is a[0], the first row, which decays to a pointer of type int* pointing at a[0][0].

  3. **a dereferences that pointer, giving a[0][0] = 1.

  4. a + **a + 2 = a + 1 + 2 = a + 3. Since a has type int (*)[5] (pointer to a row of 5 ints), a+3 points to the whole row a[3], not to an individual int.

  5. *(a+3) is a[3], which decays to an int* pointing at a[3][0] (value 16).

  6. *(a+3) + 3 performs ordinary pointer arithmetic on this int*, advancing 3 ints from a[3][0] to a[3][3].

  7. *(*(a+3)+3) dereferences that pointer, giving a[3][3].

  8. Row a[3] = {16, 17, 18, 19, 20}; index 3 (0-based) is 19.

  9. printf("%d\n", ...) prints this int, so the program's output is 19.

KEY IDEA

For a 2D array int a[4][5], a decays to a pointer of type int(*)[5] (pointer to a row), so a + k skips k whole rows. Inside a row, ordinary pointer arithmetic on an int* skips single ints. Evaluate the expression from the innermost * outward, tracking the type at each step.

WATCH OUT FOR

Confusing **a (which decays through two levels to give a[0][0] = 1, an int) with *a (which is a[0], decaying to a pointer to int), and then applying the wrong pointer arithmetic scale (rows of size 5 vs. single ints) at each step of *(*(a+**a+2)+3).

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

More Pointers & arrays questions