Topic: Programming in C
What is the output of the following C program?
#include <stdio.h>
int main()
{
int a[3][4] = {{2,4,6,8}, {9,10,11,12}, {13,15,17,19}};
int (*p)[4] = a;
printf("%d %d", *(*(p+1)+2), *(*(p)+5));
return 0;
}
- A. 11 10
- B. 6 4
- C. 12 11
- D. Undefined behavior
Answer: D. Undefined behavior
Explanation: The pointer `p` is a pointer to an array of 4 integers, pointing to the first row of `a`. `*(*(p+1)+2)` accesses the 3rd element of the 2nd row, which is valid and equals 11. However, `*(*(p)+5)` dereferences the 1st row and attempts to access the 6th element (`index 5`) within that 4-element row. Although memory is allocated contiguously and it may practically print 10 on some systems, the C standard strictly defines accessing out of bounds of the specific sub-array object (size 4) via pointer arithmetic as Undefined Behavior (UB).