0

Possible Duplicate:
C++ Returning multidimension array from function

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

0

4 Answers 4

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

MyArray getMyArray() {
    MyArray arr = {};
    // ...
    return arr;
};
Sign up to request clarification or add additional context in comments.

1 Comment

nice one, but i would add 2 other variables to the structure to hold the x and y size of the 2D array
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;
}

2 Comments

What is a Wector and why does it look familiar?
@Roger : Its is a vector of vectors so VVector. Its two V's not one W. ;-) I wasn't aware that this is a dupe. Voted to close.
-1

you have to return it as return **arr

2 Comments

if you have only one pointer and nothing more you cannot represent a 2D array
I have made it as **arr from *arr, now is it ok ?
-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;
  }

Comments