Reputation: 501
If I have a dynamically allocated array char* arr = new char[100];
.
1: If I want do keep the first half of the array and deallocate the last 50 how do i do that.
So I essentially with get the same pointer but I get as if i did char* arr = new char[50]
.
2: If I want do keep the second half of the array and deallocate the first 50 how do i do that.
So I essentially with get the original pointer plus 50 but I get as if i did char* arr = new char[50]
.
Can I do delete[99] arr;
and put it in a loop. I can do this by reallocating the array but I want it to be as fast as possible.
Please don't pester me about spelling and grammar I know I need to do better on that.
Upvotes: 0
Views: 323
Reputation: 22162
You cannot change the size of an allocation made via new
at all.
If the allocation is made via std::malloc
(or friends), you can in principle use std::realloc
to tell the system allocator that you don't need the second half anymore, but this is not possible for the first half and I would consider it dubious whether there would be any benefit doing this at all.
Additionally std::malloc
does not create objects before C++20 and therefore would make it quite complicated to use without undefined behavior. (In particular an array cannot be placement-newed into it realiably.)
A solution to the use case mentioned in the comments is to use two pointers instead of one in your structure: One pointer pointing to the beginning of the allocation and one pointer pointing to the beginning of the used space. You keep the first around, only to call delete[]
on it when needed, and the other can be used to indicate the beginning of the actual data.
Similarly you would keep around two pointers to the end, one to the end of the allocation and one to the end of the used part of it (or two integers denoting the sizes of both).
Upvotes: 3