通过二维数组转换成一个函数的正确方法 [英] Correct way of passing 2 dimensional array into a function
问题描述
我有一个2维数组,我通过它变成一个函数来执行某些操作。我想知道这样做的正确方法...
I have a 2-dimensional array and I am passing it into a function to carry out certain operations. I'd like to know the correct way of doing it...
#define numRows 3
#define numCols 7
#define TotalNum (numRows*numCols)
int arr[numRows][numCols] = {{0,1,2,3,4,5,6}, {7,8,9,10,11,12,13},{14,15,16,17,18,19,20}};
void display(int **p)
{
printf("\n");
for (int i = 0; i< numRows;i++)
{
for ( int j = 0;j< numCols;j++)
{
printf("%i\t",p[i][j]);
}
printf("\n");
}
}
int main() {
display(arr);
}
我得到一个错误信息:
I get an error message:
'display': cannot convert parameter1 from 'int' to 'int*'
这是传递一个2维数组到函数的正确方法?如果没有,什么是正确的方法是什么?
Is this the correct way of passing a 2-dimensional array into a function? If not, what is the correct way?
推荐答案
您应声明你的功能如下:
You should declare your function like this:
void display(int p[][numCols])
这Ç常见问题彻底地解释了原因。它的要点是,数组衰变为指针的一次,它不会递归发生。数组的数组衰变为一个指针数组,而不是成为一个指针的指针。
This C FAQ thoroughly explains why. The gist of it is that arrays decay into pointers once, it doesn't happen recursively. An array of arrays decays into a pointer to an array, not into a pointer to a pointer.
这篇关于通过二维数组转换成一个函数的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!