return two dimensional array from function in c++ [duplicate]
Possible Duplicate:
C++ Returning mult开发者_运维百科idimension array from function
how can i return two dimensional array from function in c++?
struct MyArray
{
int arr[8][8];
};
MyArray getMyArray() {
MyArray arr = {};
// ...
return arr;
};
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;
}
you have to return it as return **arr
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;
}
精彩评论