Say I have an array:

array={1, 2, 3}

but I want to be able to increase the size, and shift the data to the front, leaving 0's behind. So i want the array to turn into this:

array={1, 2, 3, 0, 0}

Where I added two to the size of the array and shifted the data over. Can I change the size of the array without deleting the data within it?

8 Years
Discussion Span
Last Post by gnarlyskim

Yes you can change the size while keeping the data , but you have to initialise a new array for example:

int x [sizeof(a)+2];

Something like that and then you can use a for loop to copy the contents and leaving the last two elements blank. hope this helps


If you used c++ <vector> class you would not have to worry about it because that class will do all the expanding for you. But if this is homework then you may or may not have that choice.


Vectors aren't covered in this class so that's a no go, but thank you for the suggestion. I fiddled with my code and wrote several ways to accomplish what I needed (funny enough, the simplest version is the only one that actually works), but I'm encountering a weird crash. I believe it may be a problem with dynamically allocated memory, so I'll look into that for a day or two and if I can't figure it out then I'll come back crying...but for now, problem solved! Thank you.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.