2011-02-25 03:51 AM
Handling 2D arrays in C
2011-05-17 05:25 AM
Well you'd better have them be of fixed dimensions if you want it to be ''easy'', otherwise you will have to manipulate and index into them manually (ie compute the position of the row/column within a flat pointer).
In Microsoft C this is passed as a pointer, it does not copy the structure onto the stack. void test(int array[3][3]) { int i, j; for(i=0; i<3; i++) for(j=0; j<3; j++) printf(''%d\n'',array[i][j]); putchar('\n'); } int main() { int i, j; int inputarray[3][3]; for(i=0; i<3; i++) for(j=0; j<3; j++) inputarray[i][j] = i + j*3; for(i=0; i<3; i++) for(j=0; j<3; j++) printf(''%d\n'',inputarray[i][j]); putchar('\n'); test(inputarray); return(1); } I'd be tempted to do this as a structure myself, especially if dimensions have to follow the array around to other procedures/functions. void test(int *array, int x, int y) { int i, j; for(i=0; i<x; i++) for(j=0; j<y; j++) printf(''%d\n'',array[(i * y) + j]); // array[i][j] putchar('\n'); } #define ARRAY_X 3 #define ARRAY_Y 5 int main() { int i, j, k; int inputarray[ARRAY_X][ARRAY_Y]; k = 0; for(i=0; i<ARRAY_X; i++) for(j=0; j<ARRAY_Y; j++) inputarray[i][j] = k++; for(i=0; i<ARRAY_X; i++) for(j=0; j<ARRAY_Y; j++) printf(''%d\n'',inputarray[i][j]); putchar('\n'); test((void *)inputarray, ARRAY_X, ARRAY_Y); return(1); }