Spread the love
A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a function can be difficult to remember. One important thing for passing multidimensional arrays is, first array dimension does not have to be specified. The second (and any subsequent) dimensions must be given or using single or double pointer. According to my opinion pointer is best way if you can deal with it properly.
Method 1 – When second dimension is known
/* When second argument is known */ #include <stdio.h> const int n = 3; void print(int arr[][n], int m) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf("%d ", arr[i][j]); } int main() { int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr, 3); return 0; }
Drawback :- The above method is fine if second dimension is fixed and is not user specified
Method 2 – Using Single Pointer
/* Using Single Pointer */ #include <stdio.h> void print(int *arr, int m, int n) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf("%d ", *((arr+i*n) + j)); } int main() { int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int m = 3, n = 3; print((int *)arr, m, n); return 0; }
Method 3 – Using an array of pointers or double pointer
/* Using an array of pointers or double pointer */ #include <stdio.h> // Same as "void print(int **arr, int m, int n)" void print(int *arr[], int m, int n) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf("%d ", *((arr+i*n) + j)); } int main() { int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int m = 3; int n = 3; print((int **)arr, m, n); return 0; }