Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int(&)[3] func(int (&arr) [3])
{
    // some code...
    return arr;
}

But it doesn’t work. Here is the code in online compiler: https://onlinegdb.com/copdH5Qrt

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading