there! I am new to c++ and encountered a problem of deleting pointer to an array. There was a similar question before if you search "how to properly delete a pointer to array". The conclusion of it is that it's a good habit to keep constent in using new
and delete
. If you use new <data-type> []
to allocate momery, delete[]
should follow.
I am not satisfied with this answer. What does computer do when delete
or delete[]
is excuted? So, I tried this.
#include <iostream>
using namespace std;
int main()
{
int* pvalue = NULL;
pvalue = new int[3];
cout << "address of pvalue:" << pvalue << endl;
for (int i = 0; i < 3; ++i)
{
*(pvalue+i) = i+1;
}
for (int i = 0; i < 3; ++i)
{
cout << "Value of pvalue : " << *(pvalue+i) << endl;
}
delete pvalue;
cout << "address of pvalue:" << pvalue << endl;
for (int i = 0; i < 3; i++)
{
cout << "Value of pvalue : " << *(pvalue+i) << endl;
}
return 0;
}
The output is:
address of pvalue:0x150e010
Value of pvalue : 1
Value of pvalue : 2
Value of pvalue : 3
address of pvalue:0x150e010
Value of pvalue : 0
Value of pvalue : 0
Value of pvalue : 3
Address of that pointer is not NULL
as I expected, and only two values are deleted.
If I substitute delete pvalue
to delete [] pvalue
, I would expect that all three values of array are deleted. But, the result is the same.
- Does
delete pvalue
tell the computer that this address is free to use somewhere else and doesn't actually change the address that pvalue holds? - Does
delete pvalue
ordelete [] pvalue
change the values that pointer points to? - What's the difference between
delete pvalue
anddelete [] pvalue
? It seems like that they behave the same.