Jump to content
  • Advertisement
Sign in to follow this  
nuclear123

allocate to end of array?

This topic is 2708 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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

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 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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!