0

Possible Duplicate:
C++ Returning multidimension array from function

how can i return two dimensional array from function in c++?

Community
  • 1
  • 1

4 Answers4

2
struct MyArray
{
    int arr[8][8];
};

MyArray getMyArray() {
    MyArray arr = {};
    // ...
    return arr;
};
Alexey Malistov
  • 26,407
  • 13
  • 68
  • 88
1

Use a std::vector <std::vector<T> > instead of using C style arrays.

For example:

typedef std::vector<std::vector <int> > VVector;

VVector func()
{
    VVector abc;
    //push_back and stuffs
    return abc;
}
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
-1

you have to return it as return **arr

agf
  • 171,228
  • 44
  • 289
  • 238
Anurag
  • 956
  • 2
  • 8
  • 21
-4

using an STL vector or other STL container is one way of doing it.

Another way would be to return a pointer to a pointer , since a 2 dimensional "array" is nothing more then a pointer to a pointer so in practice it looks like this

int **func_return()
{
    int **ppArray = NULL;
   ....do stuff here....

    return ppArray;
}

Note: in 99% cases you have to know how big the array is, so you also have to return the actual size of the array. for this purpose you could use the function parameters , for example

 int **func_return(std::size_t &xsize, std::size_t &ysize)
 {
        int **ppArray = NULL;
       ....do stuff here....

        return ppArray;
  }
Marek Szanyi
  • 2,348
  • 2
  • 22
  • 28