Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - Passing a variable length 2D array 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...