在 C 程序中的函数中传递二维数组 [英] Passing a 2D array in a function in C program
问题描述
下面的程序(一个将数组传递给函数的玩具程序)无法编译.请解释一下,为什么编译器无法编译(无论是技术原因还是标准原因?)
Below program (a toy program to pass around arrays to a function) doesn't compile. Please explain me, why is the compiler unable to compile(either because of technical reason or because of standard reason?)
我也会看一些解释指针/多维数组的书(因为我对这些不太了解),但这里的任何现成的指针都应该有用.
I will also look at some book explaining pointers/multi dimensional arrays(as I am shaky on these), but any off-the-shelf pointers here should be useful.
void print2(int ** array,int n, int m);
main()
{
int array[][4]={{1,2,3,4},{5,6,7,8}};
int array2[][2]={{1,2},{3,4},{5,6},{7,8}};
print2(array,2,4);
}
void print2(int ** array,int n,int m)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
printf("%d ",array[i][j]);
printf("\n");
}
}
推荐答案
这(像往常一样)在 c 常见问题解答.简而言之,数组只衰减一次为指针(衰减后,结果指针不会进一步衰减).
This (as usual) is explained in the c faq. In a nutshell, an array decays to a pointer only once (after it decayed, the resulting pointer won't further decay).
一个数组数组(即一个C 中的二维数组) decays到一个指向数组的指针,而不是一个指向指针的指针.
An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer.
最简单的解决方法:
int **array; /* and then malloc */
这篇关于在 C 程序中的函数中传递二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!