Reputation:
In C++, how to pass two dimensional array as parameter in a function and this function returns a two dimensional array?
if I have a array defined like this:
struct Hello
{
int a;
int b;
};
Hello hello[3][3] = {.......};
how to return the array above in a function?
Upvotes: 1
Views: 542
Reputation: 9144
Hardly readable (typedef is recommended), but you can do it:
Hello(&f(Hello(&A)[3][3])) [3][3] {
// do something with A
return A;
}
You actually do not need to return if this is the same array. Return void
instead - syntax will be much simpler.
Upvotes: 1
Reputation: 1580
I'd do it like this...
typedef std::vector< int > vectorOfInts;
typedef std::vector< vectorOfInts > vectorOfVectors;
vectorOfVectors g( const vectorOfVectors & voi ) {
std::for_each( voi.begin(), voi.end(), [](const vectorOfInts &vi) {
std::cout<<"Size: " << vi.size() << std::endl;
std::for_each( vi.begin(), vi.end(), [](const int &i) {
std::cout<<i<<std::endl;
} );
} );
vectorOfVectors arr;
return arr;
}
int main()
{
vectorOfVectors arr( 10 );
arr[0].push_back( 1 );
arr[1].push_back( 2 );
arr[1].push_back( 2 );
arr[3].push_back( 3 );
arr[3].push_back( 3 );
arr[3].push_back( 3 );
g( arr );
return 0;
}
Upvotes: 0
Reputation: 132984
The answer depends on what you mean by a two-dimensional array.
The C++ way would be to have a std::vector<std::vector<Type> >
, in which case the answer is like this
typedef std::vector<std::vector<myType> > Array2D;
Array2D f(const Array2D& myArray)
{
}
If you've allocated your array dynamically in Type**
as in
Type** p = new Type*(n);
for(int i = 0; i < n; ++i)
{
p[i] = new Type(m);
}
then you can simply pass the Type** along with the dimensions.
... f(Type** matrix, int n, int m);
If you have a normal 2D array as
Type matrix[N][M];
then you can pass it as
template<int N, int M>
... f(Type (&matrix)[N][M]);
I have deliberately left the return type in the two previous examples blank because it depends on what are you returning (the passed array or a newly created one) and the ownership policy.
Upvotes: 4