Difficulty: Medium
Correct Answer: 1, 1, 1, 1 2, 2, 2, 2 2, 2, 2, 2 3, 3, 3, 3
Explanation:
Introduction / Context:
The code linearizes a 2x2 matrix into an int* sequence and then indexes through an auxiliary pointer array p. The goal is to track how the four printed expressions reference the same underlying sequence.
Given Data / Assumptions:
Concept / Approach:
((p+i)+j) dereferences p[i] then offsets by j; similarly, the mixed forms ((j+p)+i), ((i+p)+j), and ((p+j)+i) are algebraically equivalent indexings into the same linear buffer because addition of integers to pointers is commutative in this form. Due to the chosen p entries, the results align to 1,2,2,3 for the four loop positions.
Step-by-Step Solution:
(i=0,j=0): dereference &a[0][0] → 1 across all four expressions.(i=0,j=1): base is &a[0][0] or &a[0][0]+1 → value 2 on each expression.(i=1,j=0): base becomes &a[0][0]+1 or +2 → value 2 on each expression.(i=1,j=1): value 3 across the four expressions given the constructed p.
Verification / Alternative check:
Print the addresses from p and compare with &a[0][0]+k to see equivalence explicitly.
Why Other Options Are Wrong:
They assume index permutations produce 3 or 4 where 1–3 appear, or they treat each expression as distinct indexing into rows/columns when in fact p is linearized.
Common Pitfalls:
Forgetting that casting (int*)a linearizes the 2D array and overlooks true row boundaries.
Final Answer:
1, 1, 1, 1 2, 2, 2, 2 2, 2, 2, 2 3, 3, 3, 3
Discussion & Comments