Passing a two-dimensional array of variable length to a function

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 pass it to a function whose prototype is:

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

      

No problems. But when I declare 2D array like VLA ie

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 this so? Is there a way that we can pass the 2nd 2D array (arr2) to the function?

I know there are many similar questions, but I haven't found one that addresses the same issue.

+3


source to share


1 answer


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

If you have

int arr2[r][c];

      

and you want to use it to call a function, the function must be declared like:



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

      

and call it

fun(r, c, arr2);

      

+6


source







All Articles