zch*_*kui 0 c pointers multidimensional-array
大家.
我使用Visual Studio 2013(C++)并在main函数中定义了一个二维数组:
int _tmain(int argc, char **argv)
{
int g[3][3] = { { 1, 2, 3, }, { 4, 5, 6, }, { 7, 8, 9, }, };
...
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后,我在定义1中定义了一个函数:
定义1:
void print_array(int **arr, int kx, int ky)
{
for (int i = 0; i < kx; i++) {
for (int j = 0; j < ky; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
我想从main函数调用这个函数:
int _tmain(int argc, char **argv)
{
int g[3][3] = { { 1, 2, 3, }, { 4, 5, 6, }, { 7, 8, 9, }, };
print_array(g, 3, 3);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
视觉工作室告诉我:
Error 1 error C2664: 'void print_array(int **,int,int)' : cannot convert argument 1 from 'int [3][3]' to 'int **'
Run Code Online (Sandbox Code Playgroud)
我也知道另一种定义方法:
定义2
void print_array(int (*arr)[3], int kx, int ky)
{
for (int i = 0; i < kx; i++) {
for (int j = 0; j < ky; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
现在它有效.
我的问题是:我之前已经重新编程它们(定义1和定义2)在旧编译器中都有用,命名为可以将数组名称作为int **或int (*p) []正确地传递给另一个函数.但是在Visual Studio C++中却没有.Visual Studio C++比其他编译器更严格吗?或者我做错了什么?
非常感谢你!
之前他重新编写它们(定义1和定义2)在旧编译器中都有效,
如果内存是正确的,旧的编译器就会被破坏.代码永远不会有效C.
您可以自由地将数组转换int x[3]为指针int *p.这一直有效,并且在很多情况下它会隐式发生.
但是,它int (*x)[3]是一个指针并且int **y是一个指针,但它们指向完全不同类型的对象!您无法将a转换int *为double *其中之一.
如果你把它们画出来,你可以看到x并y有不同的结构:
+-------------+ +-----+
| int (*x)[3] | ----> | int |
+-------------+ | --- |
| int |
| --- |
| int |
+-----+
| ... |
+---------+ +-------+ +-----+
| int **y | ----> | int * | ----> | int |
+---------+ +-------+ +-----+
| ... | | ... |
Run Code Online (Sandbox Code Playgroud)
它们看起来一点也不一样,是吗?