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 dimension