Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an array ... rather a reference or pointer to an array

Tags:

c++

arrays

return

I am a bit confused. There are two ways to return an array from a method. The first suggests the following:

typedef int arrT[10];
arrT *func(int i);

However, how do I capture the return which is an int (*)[]?

Another way is through a reference or pointer:

int (*func(int i)[10];

or

int (&func(int i)[10];

The return types are either int (*)[] or int (&)[].

The trouble I am having is how I can assign a variable to accept the point and I continue to get errors such as:

can't convert int* to int (*)[]

Any idea what I am doing wrong or what is lacking in my knowledge?

like image 483
user633658 Avatar asked Jun 26 '26 05:06

user633658


1 Answers

If you want to return an array by value, put it in a structure.

The Standard committee already did that, and thus you can use std::array<int,10>.

std::array<int,10> func(int i);
std::array<int,10> x = func(77);

This makes it very straightforward to return by reference also:

std::array<int,10>& func2(int i);
std::array<int,10>& y = func2(5);
like image 145
Ben Voigt Avatar answered Jun 28 '26 18:06

Ben Voigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!