0

Let say I don't want to use vector and use dynamic array ( Just a learning purpose). From this dynamic array which I have allocated I want to delete specific index.

int * array = new int[10];

delete &array[3];

When I try to do this I get SIGSEGV, Segmentation fault.

How do I delete specific index (lets say index 3 , I know its contiguous memory and it will create hole but just for learning purpose) like I am trying to do above correctly and why am I getting segmentation fault if this is my memory?

2
  • 1
    this is my memory This is memory graciously and temporary granted to you by the memory manager, in most cases. Commented Oct 11, 2016 at 20:24
  • Let say I don't want to use vector and use dynamic array ( Just a learning purpose). -- A vector isn't doing anything magical. Whatever vector does to delete in the middle, you have to do the same thing. Commented Oct 11, 2016 at 21:01

3 Answers 3

6

You can't delete an element of an array. You can only delete what you new'ed. To remove an element from an array, copy the higher elements down one slot.

Sign up to request clarification or add additional context in comments.

2 Comments

"You can only delete what you new'ed" Basically I didn't new'ed &array[3] that's why I can't delete it? But I new'ed array so I can delete array right? Makes sense
@pokche - exactly. delete always and only goes with new.
4

You can't. The array are stored as continuous memory location. You can't delete from in between.

Comments

2

You'd have to have an array of pointers to be able to delete a single element of your array.

You can shift all following elements back one place, but reallocation of newed memory is not possible with just the standard tools.

Or you can allocate a new array and copy all elements that you want to it.

But the easiest way is to simply use std::vector and std::vector::erase.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.