Possible Duplicate:
delete[] supplied a modified new-ed pointer. Undefined Behaviour?
Let's say I've allocated a handful of characters using new char[number]
.
Will it be possible to delete only a few end characters (something like delete[] (charArray + 4);
, which will supposedly de-allocate all of characters except for the first four)?
I read that some implementations' new[]
store the number of objects allocated before the array of objects so that delete[]
knows how many objects to de-allocate, so it's probably unsafe to do what I'm asking...
Thanks.
EDIT:
Is manually deleting the unwanted end bytes using separate delete
statements a safe way to do what I'm asking?
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
No, you have to delete[]
exactly the same pointer you get back with new[]
.
You can't delete a specific segment of an array.
If you're just operating on C strings, you can set a character to \0
and any functions that operate on the string will stop there, as C strings are null-terminated.
If you actually need to free up that memory, the closest you can get would be to make a new, smaller array, copy the elements over, and delete[]
the old array.
char* TenCharactersLong = new char[10];
// ...
char* FirstFiveCharacters = new char[5];
for (std::size_t Index = 0; Index < 5; Index++)
{
FirstFiveCharacters[Index] = TenCharactersLong[Index];
}
delete[] TenCharactersLong;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With