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)
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];
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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With