int main()
{
int size, i;
double* p;
size = 100;
p = newdouble[size];
for (i = 0; i < size; i++)
p[i] = 0.0;
changeArray(p, size);
for (i = 0; i < size; i++)
cout << p[i] << endl;
delete [] p;
return 0;
}
Snippet 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{
int size, i;
double* p;
size = 100;
p = changeArray(size);
for (i = 0; i < size; i++)
cout << p[i] << endl;
delete [] p;
return 0;
}
changeArray() is as follows:
For snippet 1:
1 2 3 4 5
void changeArray(double* arr, int length)
{
for (i = 0; i < length; i++)
arr[i] = (i + 1) * (i + 1);
}
For snippet 2:
1 2 3 4 5 6 7 8 9 10
double* changeArray(int length)
{
double* temp;
temp = newdouble[length];
for (i = 0; i < length; i++)
temp[i] = (i + 1) * (i + 1);
return temp;
}
Both snippets do the same thing.
I understand that in snippet 1 some memory is allocated for arr but once the function changeArray has been exit arr is automatically deleted. While inside the function changeArray I had two variables p and arr occupying some part of the heap. After the changeArray function was ended, then only p is in the heap until it is deleted before return in main().
For snippet 2 while inside function changeArray I have one variable (temp) occupying some part of the heap, but since the function returns a pointer to a double once the function has been exit I end up with two variables in the heap, p and temp. Is that correct? or temp is automatically deleted?.
Based on that, should be snippet 1 be more efficient in terms of memory manage and also in speed?
My other doubt is, how can I write both snippets using vector class? Can someone guide me on this?
'temp' is pushed onto the stack. '*temp' is in the heap. When the function returns, 'temp', along with all other non static local variables, is popped off the stack and no longer consumes memory. The array it was pointing to, however, remains in memory until its manually deallocated by means of delete.
Thanks for your reply. I still have a doubt. For snippet 2 after changeArray() has been exit and before delete [] in main(). Do I have two arrays in the heap, namely *p and *temp? and how about snippet 1? Are array and *array automatically deleted after changeArray() has been exit?
I guess I understood. Since temp has been deleted *temp is now pointed by p. So, I have just one array in the heap. Is that correct? The same for array and *array. So, are both snippet equally efficient in terms of memory?
p points to the same address temp used to point to. So no.
I don't see any array variable, so I assume you mean arr. arr is a local variable and follows the same rules all local variables follow. The array arr points to is inside the heap, and even if it was on the stack, it would've had to have been pushed before the the call to the function, so there's no situation where *array is deallocated after changeArray() returns.
EDIT: They are equivalent. Neither is more or less efficient than the other. Well, 2 passes one less parameter, but that's negligible.