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?
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]toarr[0][4], with values . - Row 1 contains
arr[1][0]toarr[1][4], with values . - Row 2 contains
arr[2][0]toarr[2][4], with values . - Row 3 contains
arr[3][0]toarr[3][4], with values .
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] + 0points toarr[1][0](index 5 overall)arr[1] + 4points toarr[1][4](index 9 overall)arr[1] + 5points toarr[2][0](index 10 overall)arr[1] + 9points toarr[2][4](index 14 overall)
Dereferencing *(arr[1] + 9) accesses arr[2][4]. The value assigned in the loop was:
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.