How to pass two dimensional array of an unknown size to a function
Multi-dimensional arrays are not very well supported by the built-in components of C and C++. You can pass an N
-dimension array only when you know N-1
dimensions at compile time:
calculateDeterminantOfTheMatrix( int matrix[][123])
However, the standard library supplies std::vector
container, that works very well for multi-dimension arrays: in your case, passing vector<vector<int> > &matrix
would be the proper way of dealing with the task in C++.
int calculateDeterminantOfTheMatrix(vector<vector<int> > &matrix) {
int res = 0;
for (int i = 0 ; i != matrix.size() ; i++)
for(int j = 0 ; j != matrix[i].size() ; j++)
res += matrix[i][j];
return res;
}
As an added bonus, you wouldn't need to pass dimensions of the matrix to the function: matrix.size()
represents the first dimension, and matrix[0].size()
represents the second dimension.
C solution:
In C you can't omit array size (except leftmost) when passing as function parameter.
You can write: int a[]
but can't: int a[][]
just for example: int a[][20]
This constraint is here, because compiler needs to determine proper offsets for accessing array elements. However, you can make it this way:
void print_arbitrary_2D_array(void *arr, int y, int x)
{
/* cast to 2D array type */
double (*p_arr)[y][x] = (double (*)[y][x]) arr;
int i, j;
for (i = 0; i < y; ++i) {
for (j = 0; j < x; ++j)
printf(" %lf", (*p_arr)[i][j]);
putchar('\n');
}
}
double arr_1[4][3] = {
{ 3.3, 5.8, 2.3 },
{ 9.1, 3.2, 6.1 },
{ 1.2, 7.9, 9.4 },
{ 0.2, 9.5, 2.4 }
};
double arr_2[2][5] = {
{ 3.6, 1.4, 6.7, 0.1, 4.2 },
{ 8.4, 2.3, 5.9, 1.4, 8.3 }
};
print_arbitrary_2D_array(arr_1, 4, 3);
putchar('\n');
print_arbitrary_2D_array(arr_2, 2, 5);
There are multiple approaches you could take.
C way of doing things -> Pass in a
int**
but be extremely cautious here. This is not quite a 2D array. You will have to correctly allocate memory to this pointer, or, alternatively, you need to know the size at compile time. (For instance staticly allocating an array of size M * N and then disallowing anything bigger). In order to dynamically allocate the memory, you need to know the number of rows and columns.C++ way ->
#include <vector>
after which you can simply usevector<vector<int> > &matrix
(Careful about the space after the<int>
unless you're using c++11 compiler.), which will allocate a vector of int vectors which is basically a 2d array. The memory management will be taken care of for you in this case.