将可变长度的2D数组传递给函数

将可变长度的2D数组传递给函数

问题描述:

如果我动态分配2D数组(malloc分配它),

If I dynamically allocate a 2D array(malloc it),

int r,c;
scanf("%d%d",&r,&c);
int **arr = (int **)malloc(r * sizeof(int *));

for (i=0; i<r; i++)
     arr[i] = (int *)malloc(c * sizeof(int));

,然后将其传递给原型为:

and then later on pass it to a function whose prototype is:

fun(int **arr,int r,int c)

没有问题.但是当我声明像VLA这样的2D数组时,

There is no issue. But when I declare a 2D array like VLA i.e.

int r,c;
scanf("%d%d",&r,&c);
int arr2[r][c];

当我尝试将其传递给相同的函数时,它给我一个错误.为什么会这样呢? 有什么方法可以将第二个2D数组(arr2)传递给函数?

It gives me an error when I try to pass it to the same function. Why is it so? Is there any way by which we can pass the 2nd 2D array(arr2) to a function?

我知道有很多类似的问题,但是我没有找到一个解决相同问题的问题.

1D数组会衰减为指针.但是,二维数组不会衰减到指向指针的指针.

A 1D array decays to a pointer. However, a 2D array does not decay to a pointer to a pointer.

有空

int arr2[r][c];

并且您要使用它来调用函数,则该函数需要声明为:

and you want to use it to call a function, the function needs to be declared as:

void fun(int r, int c, int arr[][c]);

并用

fun(r, c, arr2);