Amazon Interview Question
Country: India
From the C99 Standard.
6.5.2.1 Array subscripting
Constraints
1
One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall
have integer type, and the result has type ‘‘type’’.
Semantics
2 A postfix expression followed by an expression in square brackets [] is a subscripted
designation of an element of an array object. The definition of the subscript operator []
is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that
apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the
initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th
element of E1 (counting from zero).
3 Successive subscript operators designate an element of a multidimensional array object.
If E is an n-dimensional array (n ≥ 2) with dimensions i × j × . . . × k, then E (used as
other than an lvalue) is converted to a pointer to an (n − 1)-dimensional array with
dimensions j × . . . × k. If the unary * operator is applied to this pointer explicitly, or
implicitly as a result of subscripting, the result is the pointed-to (n − 1)-dimensional array,
which itself is converted into a pointer if used as other than an lvalue. It follows from this
that arrays are stored in row-major order (last subscript varies fastest).
Either order is fine. It is just a matter of design. C followed row-major order.
- Anonymous January 02, 2013For example Fortran uses column major order, meaning contiguous elements are stored column by column.
[1 2 3]
[4 5 6]
R major - 1 2 3 4 5 6
C major - 1 4 2 5 3 6
However, the following are key points,
1. The compiler designer should keep in mind the order and calculate offset accordingly.
2. Accessing contiguous elements is faster than accessing displaced elements due to cache.
3. Semantics of passing multidimensional arrays will change.