20,380 views

Consider the following $\text{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?

1. $14$
2. $20$
3. $24$
4. $30$

### 1 comment

Row Major Order is used in C Language, therefore the following mapping between logical 2D array to physical 1D memory happens in a C program.

With this idea in mind, We will also note that

arr[1] is a pointer to the first element of the 1st row.

To get to arr[1] + 9, we need to follow the row-major order.

## 9 Answers

// a[1]= &a[1][0]

//*(&a[1][0])=10

and &a[1][0]+9 = address of 9th element after the element 10.

so, *(&a[1][0]+9) = 24

After the for loop, the arr[4][5] will look like below table

 0 1 2 3 4 10 11 12 13 14 20 21 22 23 24 30 31 32 33 34

Now *(arr[1]+9) can be translated as: *(*(arr+1)+9)
Now step by step resolving it:

 0 1 2 3 4 10 *(arr[1]+0) 11 *(arr[1]+1) 12 *(arr[1]+2) 13 *(arr[1]+3) 14 *(arr[1]+4) 20 *(arr[1]+5) 21 *(arr[1]+6) 22 *(arr[1]+7) 23 *(arr[1]+8) 24 *(arr[1]+9) 30 31 32 33 34

Hence C. 24 is the answer.

If you the know the subtle difference between (a+1) and *(a+1) this can be solved within 30 seconds.

(a+1) → points to the entire 2nd row. It is a pointer to and integer array of size 5.

*(a+1) → points to the 1st element of the 2nd row. It is a pointer to an integer.

Now *(arr[1] + 9) can be interpreted as *(*(arr +1) + 9)

→ Which means we need to go to the 2nd row and access the 9th element from the starting of the 2nd Row which is finally arr[2][4] = 10 * 2 + 4 = 24

To understand please refer to the diagram below:

Solution : Option (C)

Answer – Option C

After executing of for loop, Array will be –

 0 1 2 3 4 10 11 12 13 14 20 21 22 23 24 30 31 32 33 34

Now ,

printf(“%d”, *(arr[1]+9));

arr[1] means address of first integer of second row ( as Index starting from 0)  . arr[1]+9 = arr[1]+9*sizeof(int)

i.e arr[2][4] element which is 24

by
Answer:

6 votes
2 answers
1
2,590 views
11 votes
3 answers
2
8 votes
2 answers
3
2 votes
1 answer
4