top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

In C++ what is the difference between delete and delete[]?

+1 vote
434 views
In C++ what is the difference between delete and delete[]?
posted Dec 23, 2014 by Alwaz

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+2 votes
 
Best answer

delete[]:

Whenever you allocate memory with new[], you have to free the memory using delete[].

Delete

When you allocate memory with 'new', then use 'delete' without the brackets. You use new[] to allocate an array of values (always starting at the index 0).

answer Dec 24, 2014 by Mohammed Hussain
+1 vote

Whenever you allocate memory with 'new[]', you have to free the memory using 'delete[]'. When you allocate memory with 'new', then use 'delete' without the brackets. You use 'new[]' to allocate an array of values (always starting at the index 0).

void del()
{
int *pi = new int; // allocates a single integer

int *pi_array = new int[10]; // allocates an array of 10 integers

delete pi;
pi = 0;

delete [] pi_array;
pi_array = 0;
}
answer Mar 9, 2016 by Kritika Agarwal
0 votes

The difference is big, and very important to understand. Whenever you create an object in C++ using the new keyword you will have to delete it. Whether you use “delete” or “delete[ ]” really depends on what kind of object you are creating. This is best illustrated by an example:

void foo ( )
{
string *sp = new string[50];

string *s = new string;

delete s;

// have to use "[ ]" since sp points to an array of strings:
delete[ ] sp;

}

answer Mar 9, 2016 by Ashish Kumar Khanna
...