Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What's the difference: delete vs delete[]?

Status
Not open for further replies.

SashaBuilder3

Programmer
Jan 13, 2002
131
CA
Hi everybody,

who can explain the difference between delete and delete[] (if any)? The compiler accepts either of them, so I am not sure what is the correct way to use this operator.

Thanks,

Alexandre
 
U use delete when you only want to delete one var,and delete [] when you want to delete a whole array of them.

example:
int *mypointer;
mypointer=new int;
...
delete mypointer;
---------------
and
---------------
int *mypointer;
mypointer=new int[5];
...
delete mypointer[];
-------------------
!!!!
if you would not use the [] in the second case,
only the first element of the array would be deleted,and the other 4 would stay in memory. So you would get a memory leak.



The Muppeteer.

themuppeteer@hotmail.com

Don't eat yellow snow...
 
just a small typo (at least i have never seen it typed like that)

the
delete mypointer[]; above should be

delete[] mypointer;


Matt
 

Yes of course,sorry. The Muppeteer.

themuppeteer@hotmail.com

Don't eat yellow snow...
 
But what would be the problem of writing this:

int *mypointer;
mypointer=new int;
...
delete[] mypointer;

Thanks,
Daniel.

 
Is there a problem ? that should work fine I guess. Greetz,

The Muppeteer.

themuppeteer@hotmail.com

Don't eat yellow snow...
 
The only problem is that when you see it sometime later in code you haven't read in a while, you then might start off hunting for an array that doesn't exist or something.
Or am I the only one who'd be that forgetful? If it don't make you laugh, it ain't true.
 
You're wright,but of course one should not do such a thing,
and comment his code X-) :) Greetz,

The Muppeteer.

themuppeteer@hotmail.com

Don't eat yellow snow...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top