Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Deleting part of dynamic array

Say I have a dynamic array like:

int* integers = new int[100];

Is there a way to delete only part of the array such as:

int* integers2 = integers + 50;
delete[] integers2;

I want to not only delete everything 50 and beyond, but if I call another delete[] on the original integers array, then it would only delete the correct amount of memory and not try to delete the originally allocated amount and seg fault.

Why I want to do this: I have a data structure that is structured in levels of arrays, and I want to be able to create this data structure from a full array. So I want to be able to say

int* level1 = integers;
int* level2 = integers + 50;
int* level3 = integers + 100;

But when level 3 is no longer needed, the data structure will automatically delete[] level3. I need to know that this will behave correctly and not just destroy everything in the array. If it will then I need to just create new arrays and copy the contents over, but it would be nice to avoid doing that for performance reasons.

Edit: Everyone seems to be jumping to the conclusion that I just should use a dynamic resizing container (ie vector, deque) in the first place for my data structure. I am using levels of arrays for a good reason (and they aren't equally sized like I make it look like in my example). I was merely looking for a good way to have a constructor to my data structure that takes in an array or vector and not need to copy the original contents over into the new data structure.

like image 960
Floss Avatar asked Oct 12 '11 23:10

Floss


1 Answers

No, this will not behave correctly. You can only delete[] pointers that you got from new[], else the results are undefined and bad things might happen.

If you really need the array to get smaller you have to allocate a new one and copy the contents manually.

like image 93
sth Avatar answered Oct 27 '22 15:10

sth