Kunal
Kunal

Reputation: 511

Deleting in C++

struct item   
{ 
  unsigned int a, b, c;
};

item* items[10];    
delete items[5];    
items[5] = NULL;

The above code works

But the below method is not working

int * arr1[30];

delete (arr1+5);

I am a beginner, Please tell me why I am able to delete in case of structure pointer but not in case of int pointer

Upvotes: 2

Views: 148

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 596287

When using the (arr1+5) approach, you are passing the memory address of the array slot itself at index 5, not the int* that the slot contains. To delete the int* that is contained in the slot at index 5, you have to dereference the pointer value, eg:

delete *(arr1+5);

Upvotes: 0

Stuart Golodetz
Stuart Golodetz

Reputation: 20616

You're seemingly misunderstanding what delete is for: it's purely and simply to release memory allocated by new, not to 'delete' elements of arrays.

So you might use it like this:

int *p = new int;
//...
delete p;

When you allocate arrays, you must instead use delete[], like this:

int *q = new int[23];
//...
delete [] q;

But at no point should you try and delete something that hasn't been new'ed, or use the non-matching version of delete, e.g. delete [] p; or delete q; above.

If what you really want is some sort of 'array' from which you can remove elements, try this:

#include <vector>

struct item
{
    unsigned int a, b, c;
};

int main()
{
    std::vector<item> items(10);
    items[5].a = 23;
    items.erase(items.begin() + 5);
    return 0;
}

Upvotes: 13

Jim Buck
Jim Buck

Reputation: 20726

Are you allocating heap memory anywhere? You are not doing so in the code above. You are lucky that the first delete does not crash.

Upvotes: 3

Related Questions