I know how to return a pointer which points to the first element of the array, but my question is how would I return actual array, not a pointer to that array if that is even possible.
Similarly to how would I pass array to a function by reference:
void print_arr(int (&arr) [3])
{
for(size_t i = 0; i < 3; ++i)
std::cout << arr[i] << ' ';
}
I thought something like this:
int(&)[3] func(int (&arr) [3])
{
// some code...
return arr;
}
But it doesn't work. Here is the code in online compiler.
std::arrayorstd::vectorinstead?decltype(auto)from your function.auto get_array() { std::array<int,3> values{1,2,3}; return values; }Do not worry about returning what seems to be a "local" variable. C++ has something called Copy elission which means that your array will not be copied when it is returned. So it is a fast solution. And for your print function :void print(const std::array<int,3>&> values)The&means a reference (so no copy) and theconstmakes sure you cannot accidentally modify the content of values while printing.