A three dimensional array in 'C' is declared as int A[x][y][z]. Consider that…
2024
A three dimensional array in 'C' is declared as int A[x][y][z]. Consider that array elements are stored in row major order and indexing begins from 0. Here, the address of an item at the location A[p][q][r] can be computed as follows (where w is the word length of an integer):
- A.
&A[0][0][0] + w(y * z * q + z * p + r)
- B.
&A[0][0][0] + w(y * z * p + z*q + r)
- C.
&A[0][0][0] + w(x * y * p + z * q+ r)
- D.
&A[0][0][0] + w(x * y * q + z * p + r)
Attempted by 4 students.
Show answer & explanation
Correct answer: B
Concept: The memory address of an element in a row-major multi-dimensional array equals the base address plus (word size × the number of elements stored before it in linear order). For an element A[p][q][r] in an array declared A[x][y][z], the count of elements skipped is found dimension by dimension, from the outermost index down to the innermost; each index contributes the size of one full 'block' at its own level, and the innermost index contributes its position directly.
Application:
In row-major order for A[x][y][z], the last index (r) varies fastest: all r-values for a fixed (p, q) are stored contiguously, then all q-values for a fixed p, then all p-values.
To reach the p-th plane, p complete planes must be skipped, and each plane holds y × z elements -- this skips p × (y × z) elements.
Within that plane, to reach the q-th row, q complete rows must be skipped, and each row holds z elements -- this skips q × z elements.
Within that row, to reach the r-th element, r elements are skipped directly.
Total elements skipped before A[p][q][r] = (y × z × p) + (z × q) + r.
Each element occupies w units of memory (the word length), so the total memory skipped = w × [(y × z × p) + (z × q) + r].
Address of A[p][q][r] = base address + memory skipped = &A[0][0][0] + w(y × z × p + z × q + r).
Cross-check:
Setting p = q = r = 0 gives &A[0][0][0] + w × 0 = &A[0][0][0], the base address itself -- as expected for the first element.
The largest valid offset, at p = x-1, q = y-1, r = z-1, evaluates to (x × y × z) - 1 elements -- exactly one less than the total element count x.y.z, confirming the formula stays within bounds across the whole array.
This confirms the address as &A[0][0][0] + w(y × z × p + z × q + r).