Search code examples
c++multidimensional-arrayvariable-length-array

Passing variable defining the size of a 2D array's elements


I'm working on some passing of arrays in C++. The following works, provided I define the array with numbers such as:

 gen0[6][7]. 

But, I cannot call the method where I send a variable as my size parameters. I realize that I probably need to something with passing them as pointers or by reference. I read elsewhere to use unsigned int, didn't work. I tried a few variations, but I'm struggling with the whole concept. Any tips/advice would be greatly appreciated!

//in main
 int col1, col2;
 col1 = rand() % 40 + 1;
 col2 = rand() %  50 +1;
 int gen0[col1][col2];
 print(gen0)

//not in main
 template<int R, int C>
 void print(int (&array)[R][C])

Solution

  • VLA (variable length arrays) is an extension of some compiler and it is done at runtime.

    whereas:

    template<int R, int C> void print(const int (&array)[R][C])
    

    is the correct way to pass multi-dimensional array by reference, this is done at compile time and is incompatible with VLA.

    A possible alternative would be to use std::vector:

    std::vector<std::vector<int>> gen0(col1, std::vector<int>(col2));
    

    And

    void print(const std::vector<std::vector<int>>& array)