How can I pass a dynamic multidimensional array to a function?

后端 未结 9 2269
再見小時候
再見小時候 2020-12-19 05:48

How can I pass a multidimensional array to a function in C/C++ ?

The dimensions of array are not known at compile time

9条回答
  •  隐瞒了意图╮
    2020-12-19 06:16

    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:

    • The number of elements in the array is (Size1 * Size2 * Size3 * ... * SizeN)
    • The memory needed is sizeof(value_type) * numOfElements
    • To access the element (index1, index2, index3, ..., indexN), use
      • ptr[ index1 + (Size1 * index2) + (Size1 * Size2 * index3) + ... ] assuming the first array index is the fastest-moving dimension

提交回复
热议问题