简体   繁体   中英

Why my I can't return an array?

I'm trying to return a pointer to an array from a function but I have an issue. When I try to output like this:

#include <iostream>

using namespace std;

int* Somma_Array(int[],int[],int);

int main()
{
    int n;
    cin>>n;
    int A[n],B[n];
    for(int i=0;i<n;i++)cin>>A[i];
    for(int i=0;i<n;i++)cin>>B[i];
    int *c=Somma_Array(A,B,n);
    for(int i=0;i<n*2;i++)cout<<c[i];
}

int* Somma_Array(int v[],int p[],int size)
{
    int r[size*2];
    for(int i=0;i<size;i++)r[i]=v[i];
    for(int i=0;i<size;i++)r[i+size]=p[i];
    return r;
}

it prints weird numbers instead of the actual number. I tried to do what this question says but it does not work. It gives me the following warning:

[Warning] address of local variable 'r' returned [enabled by default] 

I'm using bloodshed dev-c++.

You define a stack allocated array r , which is destroyed when you exit the function Soma_Array . This is one of the (many) reasons vectors are preferred to plain arrays - they handle allocation and deallocation for you.

#include <vector>

std::vector<int> getArray() 
{
    std::vector<int> a = {1, 2, 3};
    return a;
}

The following:

int r[size*2];

defines r locally. When the function exits (as in the scope of the function expires), r will be destroyed since it is bound to the function's scope. You are likely seeing junk data from the stack frame.

you could fix this by doing the following:

int* r = new int[size * 2];

The variable r will now be heap allocated and exist beyond the scope of the function.

IMPORTANT by doing this, you now must manually free r when you are done with it. So for instance, your calling code will look something like this:

int* result = Somma_Array(v, p, size);
/* ... do stuff ... */
delete[] result;

Since r is an array, note the use of delete[] instead of delete . delete[] is the correct way to destroy arrays.

A Better Alternative

Would std::vector be more what you are after? This is a much safer alternative to hand-rolled arrays. The vector is safer to use, scales automatically as you add elements, and cleans itself up nicely when it leaves scope (assuming you are using a value-type instance). Additionally, vectors can be copied and moved out of functions easily.

You cannot return arrays in C++. Especially, you should not return a pointer to a local array. You can however return a std::vector<int> :

std::vector<int> Somma_Array(int v[], int p[], int size)
{
    std::vector<int> r(2 * size);
    std::copy(v, v + size, r.begin());
    std::copy(p, p + size, r.begin() + size);
    return r;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM