Reputation: 33
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...
Upvotes: 1
Views: 456
Reputation: 5290
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.
Upvotes: 4
Reputation: 1149
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
}
Upvotes: 0