How are 3D arrays stored in C?

前端 未结 8 2305
半阙折子戏
半阙折子戏 2020-11-29 23:17

I understand that arrays in C are allocated in row-major order. Therefore, for a 2 x 3 array:

0  1
2  3
4  5

Is stored in memory as

8条回答
  •  孤城傲影
    2020-11-29 23:42

    I think you have answered your own question. Multi-dimensional arrays are stored in row-major order.

    See ANSI C specification section 3.3.2.1 (there is also a specific example):

    Successive subscript operators designate a member of a multi-dimensional array object. If E is an n -dimensional array ( n =2) with dimensions i x j "x ... x" k , then E (used as other than an lvalue) is converted to a pointer to an ( n -1)-dimensional array with dimensions j "x ... x" 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).

    For your example, you can just try it out and see - http://codepad.org/10ylsgPj

提交回复
热议问题