我想了解 C 将如何分配多维数组的数据项,以及它们的分配在机器之间是否一致。
我知道,在最低层,数据项是相邻的,但我不知道它们在更上层是如何排列的。
例如,如果我将一个 3D 数组分配为 int threeD[10][5][6]
,我可以假设 &(threeD[4][2][5 ]) + 1 == &(threeD[4][3][0])
?在所有机器上?
预先感谢您的帮助。
最佳答案
是的,数组在 C 编译器的所有实现中都按行主顺序存储。
标准说(我应用了一些重新格式化):
6.5.2.1 Array subscripting Constraints 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 a s 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).
关于c - C如何分配多维数组中的数据项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1578164/