Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete[] Array of characters [duplicate]

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?

like image 827
slartibartfast Avatar asked Jul 01 '11 03:07

slartibartfast


People also ask

How do I remove duplicate characters in an array?

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.


2 Answers

No, you have to delete[] exactly the same pointer you get back with new[].

like image 141
Xeo Avatar answered Sep 18 '22 07:09

Xeo


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;
like image 27
Maxpm Avatar answered Sep 20 '22 07:09

Maxpm