I need a bit of clarifaction here.
When you allocate memory in a dynamic memory it is depending on however you decide to increment your max of your array, so if my objective was to delete a single object in the array I would do the same as a static array, find element shift everything after it over it and decrement length? There is no way to deallocate that memory that single element is taking up because its already been set(allocated) to the entire max size, that why the statement

delete array[i];

is somewhat invalid and

delete [] array;


7 Years
Discussion Span
Last Post by power_computer

There are two separate terms to think about: "size" and "capacity". "capacity" is the storage allotted to the array. "size" is the number of elements in the array THAT YOU CARE ABOUT. The main rule is this: "size" must always be less than or equal to "capacity".

Say I want to store the following integers (in order): 5, 2, 1, 7, 9, 12, 6

That's 7 elements. "Size" is therefore 7. "Capacity" is the number of elements I reserve. It can be anything, as long as it at least 7. Let's say I make "capactity" 10. Here's what I do:

int size = 7;
int capacity = 10;
int* array = new int[capacity];
array[0] = 5;
array[1] = 2;
array[2] = 1;
array[3] = 7;
array[4] = 9;
array[5] = 12;
array[6] = 6;

Suppose I want to delete the fourth element. "capacity" stays at 10. "size" reduces by 1, to 6. Indexes 5 and 6 become indexes 4 and 5.

int indexToDelete = 4;
for (int i = indexToDelete; i < size - 1; i++)
   array[i] = array[i+1];

"capacity" is still 10, size is now 6. No resizing is done, so there is no "delete" or "new". You resize larger if size becomes greater than capacity. You resize smaller, based on whatever criteria you decide on (a common criteria is to resize smaller whenever size is half of capacity or less).

The terminology is a bit counter-intuitive - by "resize", I mean changing the arrays's CAPACITY, not changing the array's SIZE. I am definiing "capacity" and "size" as it is used in std::vector.


I keep screwing up on the code snippet and the grammar and I keep revising. Anyway, regardless, it appears you understood my main point.

Edited by VernonDozier: Lots of corrections


Thanks for the input vernon, I just needed confirmation on this, at first i was quite confused as I was trying to devise away, then I thought about it the way you explained and it made sense, I just wasn't totally sure If I was missing something here, thanks again for everyons input

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.