In C, given a 3D array and two pointers, what values are printed? Understand row-major layout and element addresses. #include <stdio.h> int main() { int arr[2][2][2] = {10, 2, 3, 4, 5, 6, 7, 8}; int *p, q; p = &arr[1][1][1]; q = (int)arr; printf("%d, %d ", *p, q); return 0; }

Difficulty: Easy

Correct Answer: 8, 10

Explanation:


Introduction / Context:
This exercise reinforces how C stores multi-dimensional arrays (row-major order) and how to interpret pointers to specific elements versus a pointer to the beginning of the array treated as a flat sequence.


Given Data / Assumptions:

  • arr is a 2 x 2 x 2 array initialized with 8 integers: 10, 2, 3, 4, 5, 6, 7, 8 in order.
  • p is set to the address of arr[1][1][1] (the last element).
  • q is set to (int)arr, the start of the contiguous memory.


Concept / Approach:
Row-major means the rightmost index varies fastest. With the provided initializer, the elements fill in natural index order. Therefore, the first element arr[0][0][0] is 10 and the last arr[1][1][1] is 8.


Step-by-Step Solution:
Evaluate *p: since p = &arr[1][1][1], dereferencing yields 8.Evaluate q: q points to the beginning of arr, which is arr[0][0][0] = 10.Thus, the output is "8, 10".


Verification / Alternative check:
List indices explicitly: arr[0][0][0]=10, [0][0][1]=2, [0][1][0]=3, [0][1][1]=4, [1][0][0]=5, [1][0][1]=6, [1][1][0]=7, [1][1][1]=8.


Why Other Options Are Wrong:
Reversing the pair (10, 2) ignores which pointer points where. "8, 1" invents a non-existent value. "Garbage values" is incorrect because all pointers used are valid and initialized.


Common Pitfalls:
Forgetting that casting to (int) and dereferencing gives the first element, not dimensions or sizes.


Final Answer:
8, 10

More Questions from Pointers

Discussion & Comments

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