Reputation: 405
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
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
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
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