Reputation: 1002
I've searched through many topics here, but they didn't seem to answer me exactly.
I'm trying to do some dynamic reallocation od arrays in C++. I can't use anything from STL libraries as I need to use this in homework where STL (vectors,...) is explicitly forbidden.
So far, I've tried to elaborate with code like this:
int * items = new int[3]; //my original array I'm about to resize
int * temp = new int[10];
for (int i = 0; i < 3; i++) temp[i] = items[i];
delete [] items; //is this necessary to delete?
items = new int [10];
for (int i = 0; i < 10; i++) items[i] = temp[i];
delete [] temp;
This seem to work, but what bothers me is the excessive number of iterations. Can't this be done anyhow smarter? Obviously, I'm working with much larger arrays than this. Unfortunately, I have to work with arrays though.
edit: When I try to do items = temp;
instead of
for (int i = 0; i < 10; i++) items[i] = temp[i];
and try to std::cout
all my elements, I end up with losing first two elements, but valgrind prints them correctly.
Upvotes: 0
Views: 139
Reputation: 500683
Yes, the first delete[]
is necessary. Without it, you'd be leaking memory.
As to the code that comes after that first delete[]
, all of it can be replaced with:
items = temp;
This would make items
point to the ten-element array you've just populated:
int * items = new int[3]; //my original array I'm about to resize
int * temp = new int[10];
for (int i = 0; i < 3; i++) temp[i] = items[i];
delete [] items; //delete the original array before overwriting the pointer
items = temp;
Finally, don't forget to delete[] items;
when you are done with the array.
Upvotes: 5
Reputation: 13207
The containers of the STL
were made to ease work like this. It is tedious, but there is not much of a choice, when you need to use C
-arrays.
The deletion of
delete [] items;
is necessary, as when you abandon the reference to the array, which you would do with assigning a new reference in
items = new int [10];
will cause a memory leak, so this is necessary.
Upvotes: 0