If P is a two-dimensional array having 10 rows and 20 columns, then which of…
2017
If P is a two-dimensional array having 10 rows and 20 columns, then which of the following cannot be used to access the element in row 2 and column 5?
Answer: D. *(P + 2 + 5) — ConceptFor a declaration T P[R][C], the expression P converts to a pointer to a row of C elements of type T. Array subscripting follows a[b] == *(a + b).…
- A.
P[2][5]
- B.
* (* (P + 2) + 5) - C.
*(P[2] + 5)
- D.
*(P + 2 + 5)
Attempted by 1117 students.
Show answer & explanation
Correct answer: D
Concept
For a declaration T P[R][C], the expression P converts to a pointer to a row of C elements of type T.
Array subscripting follows a[b] == *(a + b). Arithmetic on P moves by whole rows; after a row is dereferenced and decays to T*, arithmetic moves by individual elements.
Application
With
P[2][5],P[2]selects row 2 and the second subscript selects its element at offset 5.With
* (* (P + 2) + 5),P + 2reaches row 2, the inner dereference exposes that row,+ 5reaches offset 5 after decay, and the outer dereference yields the element.With
*(P[2] + 5),P[2]is the row-2 array; after decay, adding 5 and dereferencing yields its element at offset 5.With
*(P + 2 + 5), addition is left-associative, so it is*(P + 7). BecausePstill points to rows during both additions, this denotes row 7 rather than an individual element in row 2.
Cross-check
The expressions P[2][5], * (* (P + 2) + 5), and *(P[2] + 5) each yield a T lvalue. In contrast, *(P + 2 + 5) yields a T[20] row lvalue that decays to T* in most expressions.
Result
Therefore, *(P + 2 + 5) cannot be used to access the element at row 2, column 5.