Consider the following 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?
View worked solution
Answer: C
To find the output of the program, let's analyze how the 2D array is stored in memory and how the pointer arithmetic is evaluated.
1. Array Initialization
The array arr is declared as int arr[4][5], which has rows and columns. The elements are initialized using the formula:
Let's write down the values for the relevant rows:
- Row 1 ():
- , , , ,
- Row 2 ():
- , , , ,
2. Pointer Arithmetic and Memory Layout
In C, a 2D array is stored in row-major order as a contiguous block of memory.
- The expression
arr[1]decays to a pointer to the first element of the second row, i.e.,&arr[1][0], and has the typeint *. - Adding an integer to an
int *pointer shifts it forward by elements of typeint.
Therefore, we can map the pointer offsets starting from arr[1]:
3. Dereferencing
Dereferencing the pointer gives:
Substituting the values:
Thus, the program prints 24.
Free practice · Your answers on this page are not saved.
