传递一个二维数组在函数中的C程序 [英] Passing a 2D array in a function in C program
问题描述
以下程序(一个玩具程序来绕过阵列功能)不能编译。
请解释一下我的为什么编译器不能编译(或者因为还是技术原因,因为标准的原因是什么?)
我也会看一些书,介绍指针/多维数组(因为我对这些不可靠的),但在这里,任何离的,现成的三分球应该是有用的。
无效print2(INT **数组,整数N,INT米);主要()
{
int数组[] [4] = {{1,2,3,4},{5,6,7,8}};
INT数组2 [] [2] = {{1,2},{3,4},{5,6},{7,8}};
print2(数组,2,4);
}无效print2(INT **阵列,INT N,INT M)
{
INT I,J;
对于(i = 0; I< N;我++)
{
为(J = 0; J<米; J ++)
的printf(%d个,数组[I] [J]); 的printf(\\ n);
}
}
这(像往常一样)在Ç常见问题解释。简而言之,数组衰变为指针只有一次(后腐烂,产生的指针将不会进一步衰减)。
数组的数组(即一
用C二维数组)的衰变
成一个指针数组,而不是一个
指针的指针
块引用>最简单的方式来解决这个问题:
INT **阵列; / *然后malloc的* /
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"); } }
解决方案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).
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.
Easiest way to solve it:
int **array; /* and then malloc */
这篇关于传递一个二维数组在函数中的C程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!