Question 1Medium
What will be the output of the program?
#include <stdio.h>
int main()
{
static int a[2][2] = {1, 2, 3, 4};
int i, j;
static int *p[] = {(int*)a, (int*)a+1, (int*)a+2};
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
printf("%d, %d, %d, %d\n", *(*(p+i)+j), *(*(j+p)+i),
*(*(i+p)+j), *(*(p+j)+i));
}
}
return 0;
}- 1, 1, 1, 1 2, 3, 2, 3 3, 2, 3, 2 4, 4, 4, 4
- 1, 2, 1, 2 2, 3, 2, 3 3, 4, 3, 4 4, 2, 4, 2
- 1, 1, 1, 1 2, 2, 2, 2 2, 2, 2, 2 3, 3, 3, 3
- 1, 2, 3, 4 2, 3, 4, 1 3, 4, 1, 2 4, 1, 2,
Answer: C. 1, 1, 1, 1 2, 2, 2, 2 2, 2, 2, 2 3, 3, 3, 3
Explanation
When the value i is 0 of j is 0 then loop moves 4 time and print 1 1 1 1.
Then i is 0 and j is 1 is then loop moves 4 time and print 2 2 2 2.
When i is 1 and j is 0 is then loop moves 4 time and print 2 2 2 2.
When i is 1 and j is 1 is then loop moves 4 time and print 3 3 3 3.
Step-by-step solution
- ```c
Static int a[2][2] = {1, 2, 3, 4}
```
gives
a[0]= {1, 2} anda[1]= {3, 4}, which lie in memory as 1, 2, 3, 4. p[0]points to element 0,p[1]points to element 1, andp[2]points to element 2 of the same memory.- Each expression such as
p[i][j]orp[j][i]picks the element at position i + j, so all four forms give the same value. - For i = 0, j = 0 the value is 1; for i = 0, j = 1 and i = 1, j = 0 it is 2; for i = 1, j = 1 it is 3.
- So the output is 1, 1, 1, 1 2, 2, 2, 2 2, 2, 2, 2 3, 3, 3, 3, which is option C.
Why the other options are wrong
- A. The second line shows 2, 3, 2, 3, but all four values on a line are equal.
- B. Values differ within a line, but all four forms give the same element.
- D. The values are printed in array order, but each line repeats one element.
Tip: p[i][j] with a pointer array reduces to base + i + j.