简体   繁体   中英

How to pass a dynamic 2d char array to a function in C?

I know that when I am passing a 2d array to a function in c I write

int test(myarray[][5]){
//something
}
int main(void){
//something
test(myarray);
return 0;
}

This is when I have 5 collumns, but how do I do it if at the beginning of the program I scan for example number of rows and collumns so it's like

scanf("%d %d", &rows, &collumns);
char myarray[rows][collumns];
test(myarray);

what should be in the declaration of my test function, I know I can't put 5 like I did in the first code, and I can't put the max value like 1000, and if I put

int test(myarray[][collumns])

it says that collumns isn't defined in my function...

Pass another variable that sets the width. This is a c99 feature.

void test( size_t width , char myarray[][width] )
{
}

You would call it like this: test( collumns , array );

myarray behaves exactly like array in the main. ( except that myarray is actually a pointer, so sizeof operator will give you the size of a pointer, not array )

You should also pass the height( rows in you example ) of the array, unless that information is known somehow.

You can use dynamic memory allocation

int main() {
    int i;
    char **myarray;
    scanf("%d %d", &rows, &collumns);
    myarray = (char**)malloc(rows);   //Memory allocation for rows
    for(i=0;i<rows;i++) {
    myarray[i] = (char*)malloc(columns);    //Memory allocation for colums
    }
    test(myarray);
}

int test(char** arr) {
  //Write your code as it is
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM