Question

Consider the following ANSI C program.

#include <stdio.h>
int main() {
    int arr[4][5];
    int i, j;
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 5; j++) {
            arr[i][j] = 10 * i + j;
        }
    }
    printf("%d", *(arr[1] + 9));
    return 0;
}

What is the output of the above program?

Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2021 answer key

Solution

Trace row-major memory addressing and pointer arithmetic for a two-dimensional array in C.

The array is declared as int arr[4][5], which contains 4 rows of 5 integers each. In row-major order, elements are laid out contiguously in memory row by row:

  • Row 0 contains arr[0][0] to arr[0][4], with values 0,1,2,3,40, 1, 2, 3, 4.
  • Row 1 contains arr[1][0] to arr[1][4], with values 10,11,12,13,1410, 11, 12, 13, 14.
  • Row 2 contains arr[2][0] to arr[2][4], with values 20,21,22,23,2420, 21, 22, 23, 24.
  • Row 3 contains arr[3][0] to arr[3][4], with values 30,31,32,33,3430, 31, 32, 33, 34.

The expression arr[1] evaluates to a pointer of type int* pointing to the first element of row 1, &arr[1][0].

Adding an offset of 9 using pointer arithmetic advances the pointer by 9 int elements:

  • arr[1] + 0 points to arr[1][0] (index 5 overall)
  • arr[1] + 4 points to arr[1][4] (index 9 overall)
  • arr[1] + 5 points to arr[2][0] (index 10 overall)
  • arr[1] + 9 points to arr[2][4] (index 14 overall)

Dereferencing *(arr[1] + 9) accesses arr[2][4]. The value assigned in the loop was:

arr[2][4]=10×2+4=24\text{arr}[2][4] = 10 \times 2 + 4 = 24
Final answer

C

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

Source

Paper
GATE 2021 Computer Science and Information Technology - Session 2 (CS2)
Question
20 of 65, printed as CS Q.10
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.