是二维数组一个双指针? [英] Is 2d array a double pointer?
问题描述
INT的main()
{
矩阵[2] [4] = {{11,22,33,99},{44,55,66,110}};
INT ** PTR =(INT **)矩阵;
的printf(%D,**矩阵,* PTR);
}
但是,当一个2-D阵列,因为它是类型强制转换成(*矩阵)一个参数传递[2] ..
什么类型的呢编译器存储这个数组...是存储为一个2-D数组或一个双指针或指向数组的指针。如果它被存储为一个数组是怎么做的间$ P $点在不同不同的情况下像上面。请帮我明白了。
是2D的阵列中的双指针?
块引用>没有。你的程序的这一行不正确:
INT ** PTR =(INT **)矩阵;
<一个href=\"http://stackoverflow.com/questions/7351331/please-explain-the-ambiguity-in-pointers-in-c/7351390#7351390\">This与同一主题答案便宜的价格
如果你想具体的形象如何多维数组来实现:
有关多维数组的规则不是从那些普通阵列不同,刚刚替补内部数组类型的元素类型。该阵列项目后直接相互存储在内存中:
矩阵:11 22 33 99 44 55 66 110
-----------矩阵的第一元素
------------矩阵的第二元件因此,要解决的元素
矩阵[X] [Y]
,你把矩阵的基地址+ X * 4 + Y
(四是内部数组的大小)。当数组传递给函数,它们衰变为指针,以他们的第一个元素。当你注意到了,这将是
INT(*)[4]
。那么4
中的类型会告诉编译器内部类型的大小,这就是为什么它的工作原理。当类似的指针做指针算法,编译器将元素大小的倍数,所以对matrix_ptr [X] [Y]
,你得到matrix_ptr + X * 4 + Y
,这是完全一样的上方。演员
PTR =(INT **)矩阵
因此,不正确。这一次,* PTR
将意味着储存在矩阵的地址的指针值,但没有任何。其次,没有一个指针矩阵[1]
在程序的存储器中的任何注:在这篇文章的计算假设
的sizeof(int)的== 1
,以避免不必要的复杂性。int main() { matrix[2][4] = {{11,22,33,99},{44,55,66,110}}; int **ptr = (int**)matrix; printf("%d%d",**matrix,*ptr); }
But when a 2-d array is passed as a parameter it is typecasted into (*matrix)[2] .. what type does the compiler store this array as... is it storing as a 2-d array or a double pointer or an pointer to an array .. If it is storing as an array how does it interprets differently at different situations like above. Please help me understand.
解决方案Is 2d array a double pointer?
No. This line of your program is incorrect:
int **ptr = (int**)matrix;
This answer deals with the same topic
If you want concrete image how multidimensional arrays are implemented:
The rules for multidimensional arrays are not different from those for ordinary arrays, just substitute the "inner" array type as element type. The array items are stored in memory directly after each other:
matrix: 11 22 33 99 44 55 66 110 ----------- the first element of matrix ------------ the second element of matrix
Therefore, to address element
matrix[x][y]
, you takethe base address of matrix + x*4 + y
(4 is the inner array size).When arrays are passed to functions, they decay to pointers to their first element. As you noticed, this would be
int (*)[4]
. The4
in the type would then tell the compiler the size of the inner type, which is why it works. When doing pointer arithmetic on a similar pointer, the compiler adds multiples of the element size, so formatrix_ptr[x][y]
, you getmatrix_ptr + x*4 + y
, which is exactly the same as above.The cast
ptr=(int**)matrix
is therefore incorrect. For once,*ptr
would mean a pointer value stored at address of matrix, but there isn't any. Secondly, There isn't a pointer tomatrix[1]
anywhere in the memory of the program.Note: the calculations in this post assume
sizeof(int)==1
, to avoid unnecessary complexity.这篇关于是二维数组一个双指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!