Returning multidimensional array from function

Viewed 16540

How do I return a multidimensional array stored in a private field of my class?

class Myclass {
private:
   int myarray[5][5];
public:
   int **get_array();
};

// This does not work:
int **Myclass::get_array() {
    return myarray;
}

I get the following error:

cannot convert int (*)[5][5] to int** in return

7 Answers

Simpler would be decltype(auto) (since C++14)

decltype(auto) get_array() { return (myarray); } // Extra parents to return reference

then decltype (since C++11) (member should be declared before the method though)

auto get_array() -> decltype((this->myarray)) { return myarray; }
// or
auto get_array() -> decltype(this->myarray)& { return myarray; }

then typedef way:

using int2D = int[5][5]; // since C++11
// or
typedef int int2D[5][5];

int2D& get_array() { return myarray; }

as regular syntax is very ugly way:

int (&get_array())[5][5] { return myarray; }

Using std::array<std::array<int, 5>, 5> (since C++11) would have more natural syntax.

Related