Returning arrays from a function in c++

Solution 1:

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

Solution 2:

You're returning a pointer to a local object. In the uni function, the variable c is allocated on the stack. At the end of that function, all of that memory is released and in your for loop you are getting undefined results.

As suggested in the comments, std::array or std::vector will give you copy constructors that will allow you to return the object by value as you're trying to do. Otherwise you'll have to resort to something like passing your output array in as an argument.

Solution 3:

You are returning a pointer to an array that is being deallocated at the return statement. It's a dangling pointer. It's UB.

Use an std::vector or std::array and return by value. There are compiler optimizations that will avoid inefficiencies.