user2261693
user2261693

Reputation: 405

Return an array by a function in C++

It will get unexpected value:

double* myFunction()
{
    double a[2];
    a[0]=0.1;
    a[1]=0.2;
    return a;
}
int main()
{
    double* a = myFunction();
    cout<<a[0];  // it is not 0.1
    cout<<a[1];  // it is not 0.2
}

it will get expected value:

double* myFunction()
    {
        double* a = new double[2];
        a[0]=0.1;
        a[1]=0.2;
        return a;
    }
    int main()
    {
        double* a = myFunction();
        cout<<a[0];  // it is 0.1
        cout<<a[1];  // it is 0.2
    }

What is the difference between the two method?

Why the first method doesn't work correctly?

Upvotes: 0

Views: 83

Answers (3)

fatihk
fatihk

Reputation: 7919

First method uses array and an array's scope becomes garbage when program gets out of scope because it's memory allocated on the stack. However, the second method uses heap allocation in which memory is kept until delete [] is called.

If you do not work with very big arrays, you might also consider using std::vector, which combines stack and heap allocation in a sense that memory components are stored on the heap and they are deleted when you go out of scope while you do not have to call delete[] explicitly to get rid of the memory it accupies.

Upvotes: 0

taocp
taocp

Reputation: 23624

In your first way:

 double a[2];

is a local array allocated on stack, its memory will be released when exits from myFunction, so the double*will points to released memory, you saw garbage values.

double* a = new double[2];

it is also a local array allocated dynamically on the heap, however, its memory will not be released when exits from myFunction, double* will points to the that array when myFunction returns. you need to explicitly call delete[] a to release the memory.

Upvotes: 6

Keith Nicholas
Keith Nicholas

Reputation: 44288

First one allocates its array on the stack, which gets killed after the function call, second one allocated memory which doesn't get free'd up, but you will have to free it yourself later

Upvotes: 1

Related Questions