简体   繁体   English

将可变长度的二维数组传递给函数

[英]Passing a variable length 2D array to a function

If I dynamically allocate a 2D array(malloc it),如果我动态分配一个二维数组(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)

There is no issue.没有问题。 But when I declare a 2D array like VLA ie但是当我声明一个像 VLA 这样的二维数组时,即

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

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?有什么方法可以将第二个二维数组(arr2)传递给函数?

I Know there are lots of similar questions but I didn't find one which address the same issue.我知道有很多类似的问题,但我没有找到解决相同问题的问题。

A 1D array decays to a pointer.一维数组衰减为指针。 However, a 2D array does not decay to a pointer to a pointer.但是,二维数组不会衰减为指向指针的指针。

When you have当你有

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]);

and call it with并调用它

fun(r, c, arr2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM