Sign in to follow this  
31337noob

resize array?

Recommended Posts

i have a something called Shape **sPtr = 0; ok when i add new data items to it i do this. sPtr = new Shape*[num+1]; ....... ok, i think every time it finds sPtr is resizing it deletes the old data in that array. my question is how do you keep the data that is in the array when you want to resize something?

Share this post


Link to post
Share on other sites
You are dynamically creating memory on the heap. This will not delete memory previously allocated. Use the delete operator on the pointer first then allocate another array.

With that said, someone else will tell you to use the std::vector if you want an array that will resize.

If you don't use the new operator you can use the realloc command to have the memory pointed to preserved. If you take the new operator approach, then you will just have to memcpy the data over to the new array.

Share this post


Link to post
Share on other sites
Quote:
Original post by 31337noob
expect i cant use vectors because this is for homework.


Homework is supposed to be your assignment to figure out yourself. I think they call it a learning experience.


unsigned int * pIntArray = new unsigned int[20];
unsigned int * pIntArrayResize = new unsigned int[21];
memcpy(pIntArrayResize, pIntArray, sizeof(unsigned int) * 20);
delete [] pIntArray;
pIntArray = pIntArrayResize;




There is a problem with your your statement where you try to assign new char*[num + 1] to sPtr. They are unrelated types.

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