In C
can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be?
Besides, my multidimensional array may contain types other than strings.
To pass multidimensional arrays to a function, only the name of the array is passed to the function (similar to one-dimensional arrays).
Both one-dimensional arrays and multidimensional arrays can be passed as function arguments.
for (int row = 0; row<SIZE; row++) { for (int col = 0; col<SIZE; col++) { array[row][col] = 'a'; // or whatever value you want } } // Print it printarray(array, SIZE); ... Show activity on this post. Show activity on this post. You can easily pass the 2d array using double pointer.
1 #include <stdio. h> 2 #include <stdlib. h> 3 4 void print_2d_array_of_pointers(int rows, int cols, int **a) { 5 for(int i = 0; i < rows; ++i) { 6 for(int j = 0; j < cols; ++j) { 7 printf("%d ", a[i][j]); 8 } 9 printf("\n"); 10 } 11 } 12 13 // ...
Pass an explicit pointer to the first element with the array dimensions as separate parameters. For example, to handle arbitrarily sized 2-d arrays of int:
void func_2d(int *p, size_t M, size_t N) { size_t i, j; ... p[i*N+j] = ...; }
which would be called as
... int arr1[10][20]; int arr2[5][80]; ... func_2d(&arr1[0][0], 10, 20); func_2d(&arr2[0][0], 5, 80);
Same principle applies for higher-dimension arrays:
func_3d(int *p, size_t X, size_t Y, size_t Z) { size_t i, j, k; ... p[i*Y*Z+j*Z+k] = ...; ... } ... arr2[10][20][30]; ... func_3d(&arr[0][0][0], 10, 20, 30);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With