Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - Passing a multidimensional array of variable size

I'm trying to understand what "best practice" (or really any practice) is for passing a multidimensional array to a function in c is. Certainly this depends on the application, so lets consider writing a function to print a 2D array of variable size. In particular, I'm interested in how one would write the function printArry(__, int a, int b) in the following code. I have omitted the first parameter as I'm not exactly sure what that should be.

void printArry(_____, int a, int b){
/* what goes here? */
}


int main(int argc, char** argv){

int a1=5;
int b1=6;
int a2=7;
int a2=8;

int arry1[a1][b1];
int arry2[a2][b2];

/* set values in arrays */

printArry(arry1, a1, b1);
printArry(arry2, a2, b2);

}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The easiest way is (for C99 and later)

void printArry(int a, int b, int arr[a][b]){
    /* what goes here? */
}

But, there are other ways around

void printArry(int a, int b, int arr[][b]){
    /* what goes here? */
}

or

void printArry(int a, int b, int (*arr)[b]){
    /* what goes here? */
}

Compiler will adjust the first two to the third syntax. So, semantically all three are identical.

And a little bit confusing which will work only as function prototype:

void printArry(int a, int b, int arr[*][*]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...