Reputation: 333
I have a 4D array and i would like to create a function that i could use to refer to a 2D array inside the 4D array and read its data by appending square braces with indexes to the function call.
int numbers[2][3][4][4] = {
{
{{1,2,3,4}, {4,3,2,1}, {6,7,8,9}, {9,8,7,6}},
{{0,1,0,1}, {1,0,1,0}, {1,1,0,0}, {0,0,1,1}},
{{5,4,1,8}, {4,2,5,1}, {7,2,5,8}, {4,2,5,1}}
},
{ /* same stuff */ }
};
If i wanted to access just {4,2,5,1} for example, i could create a function that returns a pointer to the first int of that array (&number[0][2][1][0]), and access the elements with func()[1], func()[2], func()[3], well... you know that.
int* func() {
return &numbers[0][2][1][0];
}
// func()[2] => 5
But how could i create a function that returns a reference to numbers[0][2], so for example i could do func()[1][0]
and it would return 5?
It seems i should work up my understanding of C/C++ pointers, references and arrays, but i will also appreciate "std" and C++11-specific solutions (using some cool std::class over standard arrays). Thanks :)
Upvotes: 3
Views: 1109
Reputation: 320531
In C++ the best approach would be to return a reference to a 2D array
int (&func())[4][4] {
return numbers[0][2];
}
Now you can access it as
func()[i][j]
This fully preserves the 2D array type and keeps the natural access syntax.
If you insist on returning a pointer specifically, then you can return a pointer to the first 1D array in that 2D array
int (*func())[4] {
return numbers[0][2];
}
which will preserve the access syntax as
func()[i][j]
but, as you can see, the price of this is decay of 2D array type to 1D array type.
Or, as has already been suggested, you can return a pointer to a 2D array
int (*func())[4][4] {
return &numbers[0][2];
}
but in this case you will have to remember to access that 2D array elements as
(*func())[i][j]
i.e. it preserves the 2D array type, but forces you to use a more convoluted access syntax.
For this reason reference seems to be the best approach (as long as you insist on working with raw arrays), combining the "best" features of both pointer-based approaches.
P.S. Typedefing the 2D array type will produce much more readable function declarations. E.g. if you do
typedef int Numbers2D[4][4];
then the first variant will turn into
Numbers2D &func() {
return numbers[0][2];
}
Upvotes: 5