Passing a multidimensional array as an argument to a function. Passing one dull array as an argument is more or less trivial. Let me take a look at a more interesting case of passing a 2-dimensional array. In C, you cannot use a pointer to a pointer construct (int **) instead of a 2 dim array. Here is an example:
void assignZeros(int(*arr)[5], const int rows) { for (int i = 0; i < rows; i++) { for (int j = 0; j < 5; j++) { *(*(arr + i) + j) = 0; // or equivalent assignment arr[i][j] = 0; } }
Here I pointed out a function that takes a pointer to an array of 5 integers as the first argument. I can pass any 2-dimensional array that has 5 columns as an argument:
int arr1[1][5] int arr1[2][5] ... int arr1[20][5] ...
You can come up with a more general function that can take any 2-dimensional array and change the function signature as follows:
void assignZeros(int ** arr, const int rows, const int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { *(*(arr + i) + j) = 0; } } }
This code will be compiled, but you will get a runtime error when trying to assign values in the same way as in the first function. So in C multidimensional arrays do not match pointers to pointers ... pointers. Int (* arr) [5] is a pointer to an array of 5 elements, int (* arr) [6] is a pointer to an array of 6 elements, and they are pointers to different types!
Well, how do you define function arguments for higher dimensions? Simple, we just follow the pattern! Hier ist the same function configured to select an array of three dimensions:
void assignZeros2(int(*arr)[4][5], const int dim1, const int dim2, const int dim3) { for (int i = 0; i < dim1; i++) { for (int j = 0; j < dim2; j++) { for (int k = 0; k < dim3; k++) { *(*(*(arr + i) + j) + k) = 0;
As you would expect, as an argument, it can take any 3-dimensional arrays that have 4 elements in the second dimension and in the elements of the third dimension 5. Everything that would be in this would be good:
arr[1][4][5] arr[2][4][5] ... arr[10][4][5] ...
But we must indicate all sizes before the first.