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;

is?

Recommended Answers

All 2 Replies

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];
}
size--;

"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).


[EDIT]
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.

http://www.cplusplus.com/reference/stl/vector/
[/EDIT]

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.