How can I pass a multidimensional array to a function in C/C++ ?
The dimensions of array are not known at compile time
I'm just summarizing the options from other posts.
If the number of dimensions (the N as in N-dimensional array) is unknown, the only way is to use a C++ multidimensional array class. There are several publicly available implementations, from Boost or other libraries. See Martin Beckett's post.
If the number of dimensions is known but the array size is dynamic, see Tom's answer for accessing an array element (converting multi index into element pointer). The array itself will have to be allocated with malloc or new.
If you are writing the multidimensional array class yourself, you'll need to know about Row-major-order, Column-major-order, etc.
Namely, if the array dimensios is (Size1, Size2, Size3, ..., SizeN)
, then:
(Size1 * Size2 * Size3 * ... * SizeN)
sizeof(value_type) * numOfElements
(index1, index2, index3, ..., indexN)
, use
ptr[ index1 + (Size1 * index2) + (Size1 * Size2 * index3) + ... ]
assuming the first array index is the fastest-moving dimensionYou can pass the pointer to initial memory location of your multi dimension array. you should also pass the size of array i.e. limit of each dimension.
i.e
int var [x][y][z];
func (var, x, y, z);
function definintion:
void func (int*, int, int, int);
I think this is a GCC extension (or a quite modern C feature), but it can be quite convenient:
void foo(int bar[n][m], int n, int m) {...}