Evaluate pointer arithmetic on a 2x2 static matrix. What is printed by each expression?\n#include<stdio.h>\n\nint main()\n{\n static int a[2][2] = {1, 2, 3, 4};\n int i, j;\n static int p[] = {(int)a, (int*)a + 1, (int*)a + 2};\n for(i = 0; i < 2; i++)\n {\n for(j = 0; j < 2; j++)\n {\n printf("%d, %d, %d, %d\n", ((p + i) + j), ((j + p) + i), ((i + p) + j), ((p + j) + i));\n }\n }\n return 0;\n}

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:

  • a laid out in row-major order: [1 2; 3 4].
  • (int*)a points to &a[0][0].
  • p[0]=&a[0][0]; p[1]=&a[0][0]+1; p[2]=&a[0][0]+2.


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

More Questions from Arrays

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion