Bidimensional Arrays

How do I return a bidimensional int array, like int array[2][2], from a function?
1) Return a struct that has the info about the dimensions (and the array)
2) Do it the easier way and just return a vector of vectors.
3) Don't return a 2D array at all, because a 2D array is just a fancy 1D array anyways.
Last edited on
You don't. Arrays don't get returned from functions.

Typically you pass arrays by pointer, and have the function modify the array by pointer instead. Although this is complicated with multidimentional arrays.

See this article for techniques explainig how to pass multidimentional arrays to functions (as well as explanations why this should be avoided):

http://www.cplusplus.com/forum/articles/17108/
I'm not sure how this works with arrays (I never use them because they confuse me), but generally when you want "complicated" returns, you can pass-by-reference the object as a parameter to the function and then store it.

For example, when you want to return a vector (sort of array-like container type) of ints, it's easier to do this:

1
2
3
void returnVector(vector<int> &ints) {
(fill vector here)
}


To do the exact thing you want, you could for example do this:
1
2
3
4
5
6
7
8
9
void fillAndReturnVector(vector<vector<int>> &intArray) {
intArray.resize(2);
intArray[0].resize(2);
intArray[1].resize(2):
intArray[0][0] = 5;
intArray[0][1] = 10;
intArray[1][0] = 3;
intArray[1][1] = 6;
}


Then call it at such:

1
2
vector<vector<int>> testingArray;
fillAndReturnVector(testingArray);


That 2dimensional vector will now act just like an Array. I imagine you can do the same with actual arrays, but I don't touch the things in C++.

[edit]

Some additional explanation on the vector things: A vector has no pre-defined size. By using .resize(int), you can set the size.

The first resize call (on intArray itself) sets the first dimension of the "array"; the second and third calls set the second dimension of the "array" (a 2dimensional vector doesn't have to be a full "NxM matrix", so every row can have a different length if wanted).
Last edited on
Ok, thank you. I ended up modifying the code to a 1D array, thanks to Disch's article, so I solved the problem.
Topic archived. No new replies allowed.