问题描述
我有一个关于C / C ++如何在内部存储多维数组使用标记富[M]宣布的问题[N]
。我并不是质疑纯指针的指针等...我问的,因为速度的原因...
I have a question about how C / C++ internally stores multidimensional arrays declared using the notation foo[m][n]
. I am not questioning pure pointers to pointers etc... I am asking because of speed reasons...
纠正我,如果我错了,但是从语法富
是一个指针数组,这本身指向数组
Correct me if I am wrong, but syntactically foo
is an array of pointers, which themselves point to an array
int foo[5][4]
*(foo + i) // returns a memory address
*( *(foo + i) + j) // returns an int
我已经从很多地方听到的C / C ++编译器转换富[M] [N]
来在幕后的一维数组(计算所需的一维与索引i *宽+ J
)。但是,如果这是真的,那么下面将举行
I have heard from many places that the C/C++ compiler converts foo[m][n]
to a one dimensional array behind the scenes (calculating the required one dimension index with i * width + j
). However if this was true then the following would hold
*(foo + 1) // should return element foo[0][1]
因此,我的问题:
这是真的,富[M] [N]
是(总是?)存储在内存中的一台一维数组?如果是这样,为什么如上述code的工作。
Thus my question:Is it true that foo[m][n]
is (always?) stored in memory as a flat one dimensional array?? If so, why does the above code work as shown.
推荐答案
是的,C / C ++存储多维(矩形)阵列作为一个连续的内存区域。但是,你的语法不正确。要修改元素 foo的[0] [1]
,以下code将工作:
Yes, C/C++ stores a multi-dimensional (rectangular) array as a contiguous memory area. But, your syntax is incorrect. To modify element foo[0][1]
, the following code will work:
*((int *)foo+1)=5;
显式类型转换是必要的,因为富+ 1
,是一样的&放大器;富[1]
这是不是在所有一回事 foo的[0] [1]
。 *(美孚+ 1)
是一个指向平面内存区第五元素。换句话说, *(美孚+ 1)
基本 foo的[1]
和 * *(美孚+ 1)
是 foo的[1] [0]
。下面是内存是如何为你的一些二维阵列的布局:
The explicit cast is necessary, because foo+1
, is the same as &foo[1]
which is not at all the same thing as foo[0][1]
. *(foo+1)
is a pointer to the fifth element in the flat memory area. In other words, *(foo+1)
is basically foo[1]
and **(foo+1)
is foo[1][0]
. Here is how the memory is laid out for some of your two dimensional array:
这篇关于C / C ++多维数组内幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!