-3

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.

5
  • 5
    Use std::array or std::vector instead? Commented Jun 11, 2023 at 16:38
  • I am aware of them but I was wondering if there is a simpler solution. Commented Jun 11, 2023 at 16:42
  • 5
    What can possibly be simpler? Commented Jun 11, 2023 at 16:44
  • You could also return decltype(auto) from your function. Commented Jun 11, 2023 at 16:47
  • You could write : 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 the const makes sure you cannot accidentally modify the content of values while printing. Commented Jun 11, 2023 at 16:56

1 Answer 1

0

You cannot 'return arrays' directly in C or C++. One way you can use to get around that is declare a struct/union containing the array.

union arrayint3 {
    int i[3];
};
arrayint3 func(int(&arr)[3]) {
    arrayint3 arr = {.i = {1, 2, 3}};
    return arr;
}

You can also return an std::array. According to the linked Q&A:

Is it legal to return std::array by value, like so?

std::array<int, 3> f() {
    return std::array<int, 3> {1, 2, 3};
}

Yes it's legal.

Sign up to request clarification or add additional context in comments.

4 Comments

I would say forget about your first solution and stick with std::array. In current C++ do NOT use unions : use std::variant. See P.4 C++ core coding guidlines
@PepijnKramer Only use the first solution if pure-C compatibility is required.
I assumed this was a pure C++ question :) But yes union is one of those backward compatibility "left over" thingies.
@user16217248 What's the benefit of using a union rather than a struct?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.