1
char myWord[20];

I want to delete last 10 chars of this array, I mean freeing the memory thats being used by last 10 chars. Is there anyway to do this ?

Heres an example function for substring where it might be useful.

str& substring(uint Start, uint Count){
    for(uint x=0; x<Count; x++){
        mString[x] = mString[x+Start];
    }  
    // SOMEHOW FREE MEMORY OF mString FROM [Start+Count] TO [mLength]
    mLength = Count;
    return *this;
}
3
  • I don't think you can do this when you've allocated the memory statically (at compile-time) using []. If you use malloc() to allocate your memory dynamically, you can e.g. use realloc() to reduce/enlarge your array. Commented Jun 5, 2011 at 12:23
  • It's allocated on the stack so it will all be freed automatically when the containing block ends. Why do you need to "rush" this? Commented Jun 5, 2011 at 12:27
  • 2
    Please understand that C and C++ are very different languages, even if their syntaxes have a lot in common. Commented Jun 5, 2011 at 12:43

2 Answers 2

3

No, not really. You can really only do it if you obtained a pointer to memory from malloc, and then used realloc to change the size, but I'm quite sure that it's not even guaranteed that it will free the unused bytes.

Sign up to request clarification or add additional context in comments.

10 Comments

But this will copy the array just with different length ?
Not necessarily, it is possible that the data may end up copied somewhere else, but the end result is that you then have a pointer to memory of 10 bytes, rather than 20 (even if those 10 bytes aren't in the same place that the original 20 were).
@aeroson: 10 bytes of memory to keep/free are the last of your problems in a real application. It's probably much more inefficient to call realloc than to keep the buffer 10 bytes larger.
@aeronson: realloc is well documented and also reading documentation and understanding it is a valuable skill. go read what realloc does
@aeroson: Then use the .erase() method instead.
|
2

With stack-allocated arrays1, no. You can only use some special character to mark the "logical end" of the array; for strings usually the NUL character (0) is used.


  1. And even with stuff allocated on the heap usually you don't have that much granularity in allocations to free just 10 bytes of a 20-bytes long string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.