指针传递到在C中的指针 [英] passing a pointer to a pointer in C
问题描述
编译:
#include <stdlib.h>
void f(int ** v)
{
}
int main()
{
int v[2][3];
f(v);
return 0;
}
与失败:
g.cpp:13:8: error: cannot convert ‘int (*)[3]’ to ‘int**’ for argument ‘1’ to ‘void f(int**)’
但通过了以下变化:
But the following changes passed:
#include <stdlib.h>
void f(int ** v)
{
}
int main()
{
int * v[2];
f(v);
return 0;
}
在我看来,一个数组的更深层面具有在编译时要解决,而且可以有人阐述更多一点吗?
It seemed to me that the deeper dimensions of an array has to be solved upon compilation, and can somebody elaborate more about it?
推荐答案
C和C ++自动强制数组指针。的错误是由于这样的事实造成的,这强迫只发生一次(即仅在第一级)。这意味着 INT [10]
将得到裹挟到为int *
;但 INT [10] [10]
最多可以得到裹挟到为int * [10]
。
C and C++ automatically coerce arrays to pointers. The error is caused due to the fact that this coercion happens only once (i.e. at only the first level). This means int [10]
will get coerced to int *
; but int [10][10]
can at most get coerced to an int *[10]
.
原因与内存布局做。你看, A [I]
转化为 *(A +的sizeof(T)* I)
如果 A
是类型 T *
(假设直接添加到指针不结垢增加);但是,如果 A
的类型 T [N]
, A [I] <的/ code>转化为
*(&安培; A [0] + I)
。因此,它遵循该类型的值 T [N]
可强制转换类型的值 T *
按取第一元素的地址 - 存储器布局在这种情况下,兼容
The reason has to do with memory layout. You see, a[i]
translates to *(a + sizeof(T) * i)
if a
is of the type T *
(assume adding to pointers directly adds without scaling); but if a
is of the type T [N]
, a[i]
translates to *(&a[0] + i)
. Thus, it follows that a value of type T [N]
can be coerced into a value of type T *
by taking the address of the first element -- the memory layouts are compatible in this case.
然而,一个二维数组 A
(类型为 T [2] [4]
,说的)会比双指针存储不同(类型 T **
)。在第一种情况下,你有四个元素, T [0] [0]
到 T [0] [3]
在内存中,然后按奠定了T [1] [0]
到 T [1] [3]
和依此类推,模对齐。在第二种情况下,你就已经制定了一个接一个的一堆指针(以 T
)。在第一种情况下, A [I] [J]
将得到降低到 *(&安培; A [0] [0] +的sizeof(T )* 4 * 1 +的sizeof(T)* j)条
而在第二种情况下,它会被降低到 *(*(A +的sizeof(T)* I)+的sizeof(T)* j)条
。存储器布局不再兼容。
However, a two dimensional array a
(of type T [2] [4]
, say) will be stored differently than a double pointer (of type T **
). In the first case, you have the four elements,T [0][0]
to T [0][3]
laid out in memory followed by T [1][0]
to T [1][3]
and so on, modulo alignment. In the second case, you just have a bunch of pointers (to T
) laid out one after the other. In the first case, a[i][j]
will get lowered into *(&a[0][0] + sizeof(T) * 4 * i + sizeof(T) * j)
while in the second case it will get lowered into *(*(a + sizeof(T) * i) + sizeof(T) * j)
. The memory layouts are no longer compatible.
这篇关于指针传递到在C中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!