Alex Rivera | Logout

How to return a 2D array from a function in C++

Asked 2011-12-23T15:24:36.027
70

I am trying to return a 2D array from a function with the following code:

int **MakeGridOfCounts()
{
    int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
    return cGrid;
}
Edit
Report

1 Answer

10

That code isn't going to work, and it's not going to help you learn proper C++ if we fix it. It's better if you do something different. Raw arrays (especially multi-dimensional arrays) are difficult to pass correctly to and from functions. I think you'll be much better off starting with an object that represents an array but can be safely copied. Look up the documentation for std::vector.

In your code, you could use vector<vector<int> > or you could simulate a 2-D array with a 36-element vector<int>.

answered 2011-12-23T15:51:35.790

Your Answer