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

后端 未结 9 2271
再見小時候
再見小時候 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
    0 讨论(0)
  • 2020-12-19 06:18

    You 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);
    
    0 讨论(0)
  • 2020-12-19 06:22

    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) {...}
    
    0 讨论(0)
提交回复
热议问题