Search code examples
c++arraysreturn

How to return array in C++ not a pointer?


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.


Solution

  • 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.