Archived

This topic is now archived and is closed to further replies.

Bagpuss

Reallocating New'd data

Recommended Posts

What is the best way to resize an array allocated with new ? Is it safe to use Realloc() when you use new, or do you just call new again on the data to resize it ? Bp. [edited by - Bagpuss on October 24, 2003 11:32:19 AM]

Share this post


Link to post
Share on other sites
quote:
Is it safe to use Realloc() when you use new

No! This could work on a specific compiler/platform combination, but the behaviour is undefinded, so DON''T do that.

The C++ way for that is using a std::vector. It''s not slower if you use it correctly.

Share this post


Link to post
Share on other sites
you could use an STL vector and just forget the entire ordeal. STL vector is pretty easy to use. It's setup to be used a lot like an array


#include <vector>
using namespace std;

vector<int> vec;
vec.push_back(0);
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);

//now has 0, 1, 2, and 3 at indexes 0, 1, 2, and 3


vec[0]=5;
vec[3]=7;
//now is 5, 1, 2, 7


vec.push_back(2);
//5, 1, 2, 7, 2


vec.insert(1, 4);
//5, 4, 1, 2, 7, 2


vec.size(); //returns 6 at this point



Other than that, you will have to use a temporary pointer to the array, allocate new memory, then copy the array, element by element, then delete the temp pointer


//arr is an array of ints that's been new'ed

//it is of size 5


int * temp=arr;
arr=new int[8];
for(int i=0;i<5;i++) arr[i]=temp[i];
delete[] temp;

//arr is now of size 8



[edited by - capn_midnight on October 24, 2003 1:07:00 PM]

Share this post


Link to post
Share on other sites
The problem is I am working with byte arrays, but They are in length, data pairs. So I can read in the length, and then have to create an array of the correct length before I can read in the data. If the data is of char type, I need to append a ''\0'' after it, where as if it is int then I dont need to

Cheers,

Bp

Share this post


Link to post
Share on other sites
If you want to use your hands: call delete to free the memory allocated with new then call new again (C++ is not java!).
In C++ you must use directly only the new/delete operators; you can however redefine the new/delete operators in your class or globally (and use malloc/free in the body).




[edited by - blizzard999 on October 28, 2003 6:51:25 PM]

Share this post


Link to post
Share on other sites