Extending a dynamically allocated array. (C++)

Programming, for all ages and all languages.
Post Reply
User avatar
Zacariaz
Member
Member
Posts: 1069
Joined: Tue May 22, 2007 2:36 pm
Contact:

Extending a dynamically allocated array. (C++)

Post 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.
This was supposed to be a cool signature...
User avatar
Zacariaz
Member
Member
Posts: 1069
Joined: Tue May 22, 2007 2:36 pm
Contact:

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

Post by Zacariaz »

well, that's all I needed to know.

Thanks.
This was supposed to be a cool signature...
Post Reply