Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...