Page 1 of 1

Extending a dynamically allocated array. (C++)

Posted: Fri Feb 25, 2011 8:10 pm
by Zacariaz
As I understand it, the method that the title suggests that I'm investigating, is pretty straight forward.

Code: Select all

Type* ptr1 = new Type[i];
Type* ptr2 = new Type[i+j];
for (int n = 0; n < i; n++) {
    ptr2[n] = ptr1[n];
}
delete [] ptr1;
ptr2 = ptr1;
Assuming I haven't made any mistakes, the above code should work, though it's quite a hassle.

So I really only have two questions, the first of which is really not important, though it's still interesting as I'm not quite sure.

1. Considering the above process, would there be anyway of eliminating the need for the temporary ptr2?

2. The obvious solution to any problem involving the previously described process would of course be to use a vector instead, but what will the pros/cons be, especially regarding memory footprint? Is the workings of std::vector really that different?

I have of course tried to find the answers my self, but I've had little luck.


Thanks.

Re: Extending a dynamically allocated array. (C++)

Posted: Sat Feb 26, 2011 5:40 am
by Zacariaz
well, that's all I needed to know.

Thanks.