4

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.

3
  • 1
    I removed the C++ tag because VLAs arent' standard C++. Commented Aug 7, 2015 at 5:26
  • ok. I tried the code in c++. It was not working. Probably it won't work in c either. Commented Aug 7, 2015 at 5:29
  • 1
    You were looking for this question Commented Aug 7, 2015 at 5:34

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

2 Comments

probably you are saying arr is of type int** but arr2 is of type int *[c], right?
arr, the argument in fun, is of type int (*)[c], not int**.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.