将可变长度的2D数组传递给函数 [英] Passing a variable length 2D array to a function

查看:110
本文介绍了将可变长度的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);

这篇关于将可变长度的2D数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆