This seems like it should have a super easy solution, but I just can't figure it out. I am simply creating a resized array and trying to copy all the original values over, and then finally deleting the old array to free the memory.
void ResizeArray(int *orig, int size) {
int *resized = new int[size * 2];
for (int i = 0; i < size; i ++)
resized[i] = orig[i];
delete [] orig;
orig = resized;
}
What seems to be happening here is that resized[i] = orig[i]
is copying values by reference rather than value, as printing orig after it gets resized returns a bunch of junk values unless I comment out delete [] orig
. How can I make a deep copy from orig to resized, or is there some other problem that I am facing? I do not want to use std::vector.
std::vector
, you would gain a lot by wrapping this in a class so that clients can pass around an invariant object and not have to manage the fact that the implementation pointer is changing with every resize. :-/ – Mabuse