Can anyone tell me how can we pass a 2d array to a function in c so that its data dont get lost.Please explain with example. Thanks in advance
A:
I don't know what you mean by "data dont get lost". Here's how you pass a normal 2D array to a function:
void myfunc(int arr[M][N]) { // M is optional, but N is required
..
}
int main() {
int somearr[M][N];
...
myfunc(somearr);
...
}
casablanca
2010-10-12 03:06:48
Random factoid: The reason N is required is because the computer needs to know how far along to increment the pointer for each "row". Really, all dimensions except the first one are necessary. C stores arrays as chunks of memory, with no delimiters.
Christian Mann
2010-10-12 03:12:10
data dont get lost means without using malloc. Thanks for the help.
Shweta
2010-10-12 03:19:54
@Christian Mann: Thats a good factoid. I happened to write an elaborate explanation on it today :-) http://stackoverflow.com/questions/3906777/error-defining-and-initializing-multidimensional-array/3910533#3910533
ArunSaha
2010-10-12 05:30:18
It seems everyone is having problems with multi-dimensional arrays today. :) I wrote a similar explanation in another question too: http://stackoverflow.com/questions/3911244/confusion-about-pointers-and-multidimensional-arrays
casablanca
2010-10-12 05:34:05
A:
Bart van Ingen Schenau
2010-10-12 08:55:41
A:
If your compiler does not support VLAs, you can do it in simple way by passing the 2d array as int* with row and col. In the receiving function regenerate the 1d array index from 2d array indexes.
int
getid(int row, int x, int y) {
return (row*x+y);
}
void
printMatrix(int*arr, int row, int col) {
for(int x = 0; x < row ; x++) {
printf("\n");
for (int y = 0; y <col ; y++) {
printf("%d ",arr[getid(row, x,y)]);
}
}
}
main()
{
int arr[2][2] = {11,12,21,22};
int row = 2, col = 2;
printMatrix((int*)arr, row, col);
}
Rajneesh Gupta
2010-10-14 11:29:20