Pointer arithmetic and 2D arrays in C (row-major layout): assuming the base address of a begins at 1002 and sizeof(int) = 4 bytes, what does the following print? #include<stdio.h> int main() { int a[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; printf("%u, %u, %u ", a[0]+1, (a[0]+1), ((a+0)+1)); return 0; }

Difficulty: Medium

Correct Answer: 1006, 2, 2

Explanation:


Introduction / Context:
Understanding how C lays out multidimensional arrays (row-major order) and how pointers relate to array elements is essential for correct indexing and pointer arithmetic. This example asks you to compute both an address and two dereferenced values when given a base address and sizeof(int).


Given Data / Assumptions:

  • Array a is 3 rows by 4 columns: a[0][0]=1, a[0][1]=2, a[0][2]=3, a[0][3]=4, …
  • Base address of a is 1002 (bytes).
  • sizeof(int) = 4 bytes.
  • Row-major layout: consecutive elements in a row are adjacent in memory.


Concept / Approach:
a[0] has type int and points to a[0][0]. Adding 1 to a[0] advances the pointer by one int, i.e., +4 bytes. Dereferencing (a[0]+1) reads a[0][1]. The expression ((a+0)+1) is the same as a[0][1].


Step-by-Step Solution:

Address: a[0] → 1002; a[0] + 1 → 1002 + 1sizeof(int) = 1002 + 4 = 1006.Value: *(a[0] + 1) → element a[0][1] → 2.Value: ((a + 0) + 1) → a[0][1] again → 2.


Verification / Alternative check:
Index equivalence: a[i][j] equals ((a+i)+j). With i=0, j=1 we get the same element both ways.


Why Other Options Are Wrong:

448, 4, 4 or 520, 2, 2: Addresses do not match the given base and sizeof(int).Error: The expressions are valid and well-typed.1002, 1, 1: That would correspond to a[0] not a[0]+1, and to element [0][0], not [0][1].


Common Pitfalls:
Adding 1 to a pointer moves it by sizeof(element), not 1 byte; confusing addresses with values; forgetting row-major ordering.


Final Answer:
1006, 2, 2.

More Questions from Pointers

Discussion & Comments

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