Returning arrays from a function in c++

Admittedly, the std::vector or std::array approach would be the way to go.

However, just to round things out (and if this is a school project, where the teacher gives you the obligatory “you can’t use STL”), the other alternative that will avoid pointer usage is to wrap the array inside a struct and return the instance of the struct.

#include <iostream>

using namespace std;
struct myArray
{
   int array[10];
};

myArray uni(int *a,int *b)
{
    myArray c;
    int i=0;
    while(a[i]!=-1)
    {
        c.array[i]=a[i];
        i++;
    }
    for(;i<10;i++)
        c.array[i]=b[i-5];
    return c;
}

int main()
{
    int a[10]={1,3,3,8,4,-1,-1,-1,-1,-1};
    int b[5]={1,3,4,3,0};
    myArray c = uni(a,b);
    for(int i=0;i<10;i++)
        cout << c.array[i] << " ";
    cout << "\n";
    return 0;
}

Note that the struct is returned by value, and this return value is assigned in main.

You have the value semantics of returning an instance, plus the struct will get copied, including the array that is internal within it.

Live Example

Leave a Comment