Sign in to follow this  
nuclear123

allocate to end of array?

Recommended Posts

i know vectors exists but i'm wanting to learn how to manually do this...

i want to be able to allocate memory to the end of my array when needed or even deallocate memory when deleting a specific character. Im curious how one would achieve this manually. If anyone has any resources or examples i would appreciate it! thx

Share this post


Link to post
Share on other sites
C++ has no standard mechanism to extend the length of a memory allocation. Individual memory allocators may provide such a mechanism such as MSVC's _extend() function. What a std::vector does when it reallocates memory is create a second buffer and copy the objects from the first buffer to the second.

Share this post


Link to post
Share on other sites
[quote name='nuclear123' timestamp='1298148103' post='4776413']
i want to be able to allocate memory to the end of my array when needed or even deallocate memory when deleting a specific character. Im curious how one would achieve this manually.
[/quote]
If you want your data to be contiguous like std::vector or an array then a linked list obviously won't work.

Otherwise if you want to fake appending to an array you would create a new array, copy all the old data to the new array, and then delete the old array.

If you want to 'delete' a character from a specific index, you have 2 options depending on how stupid you want to be when deleting a character. The first, smarter option is to copy the data from the index of the character you want to delete over. so data[index]=data[index+1] and then keep copying every element until index+1 is no longer less than the size. This method assumes you are keeping track of two thigns: the usable size and the real capacity of the dynamic array. When deleting a character the size would decrease but the capacity would remain the same. This is how std::vector does it. The other option is to create a new vector and copy the data from 0 to index-1 to the new array and then the rest of the data from index+1 to the end of the old array to the new array. Then delete the old array.

If you want to look up other stuff on this topic the subject to search for would be "dynamic arrays". Once you hack something rudimentary together scrap it all and go back to std::vector.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this