C语言 在 C 程序中的函数中传递二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6321670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:54:07  来源:igfitidea点击:

Passing a 2D array in a function in C program

carrayspointersmultidimensional-array

提问by xyz

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");
    }
}

回答by cnicutar

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 常见问题解答中进行了解释。简而言之,数组只衰减一次指针(衰减后,结果指针不会进一步衰减)。

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.

数组数组(即 C 中的二维数组)衰减为指向数组的指针,而不是指向指针的指针

Easiest way to solve it:

最简单的解决方法:

int **array; /* and then malloc */

回答by Jens Gustedt

In C99, as a simple rule for functions that receive "variable length arrays" declare the bounds first:

在 C99 中,作为接收“可变长度数组”的函数的简单规则,首先声明边界:

void print2(int n, int m, int array[n][m]);

and then your function should just work as you'd expect.

然后你的函数应该像你期望的那样工作。

Edit: Generally you should have a look into the order in which the dimension are specified. (and me to :)

编辑:通常您应该查看指定维度的顺序。(和我:)

回答by Vishal Kanaujia

In your code the double pointer is not suitable to access a 2D array because it does not know its hop size i.e. number of columns. A 2D array is a contiguous allotted memory.

在您的代码中,双指针不适合访问二维数组,因为它不知道其跃点大小,即列数。二维数组是连续分配的内存。

The following typecast and 2D array pointer would solve the problem.

下面的类型转换和 2D 数组指针可以解决这个问题。

# define COLUMN_SIZE 4
void print2(int ** array,int n,int m)
{
    // Create a pointer to a 2D array
    int (*ptr)[COLUMN_SIZE];
    ptr = int(*)[COLUMN_SIZE]array;

    int i,j;
    for(i = 0; i < n; i++)
    {
       for(j = 0; j < m; j++)
       printf("%d ", ptr[i][j]);
       printf("\n");
    }
}