Skip to main content
gamedev.net
🔒 Locked

Array redimension

Started by Shadows 5 replies 2.1k views
Original Post
Shadows
Shadows
Just what it says how do I redimension an array? Regards //Shadows
MindWipe
MindWipe
int array[100];

delete array;
array = new int[1000];

/MindWipe

"If it doesn''t fit, force it; if it breaks, it needed replacement anyway."
"To some its a six-pack, to me it's a support group."
Brannon
Brannon
Just to be picky, MindWipe, that won''t work. You cant declare a static sized array (int array[100]), delete it, and then allocate new memory to it. You might be able to get away with allocating the new memory, but deleting it definitely wont work.


-Brannon
-Brannon
null_pointer
null_pointer
C++''s standard vector class is great. I would also recommend using it unless you want to learn how to do this yourself. To redimension an array, you want to do something like this:

#include <algorithm>
 
using std::copy;
using std::swap;
 
int main()
{
// p refers to the array that is to be resized
 
int* p = new int[old_size];
 
// redimension p to the new size while preserving old values
 
int* temp = new int[new_size]; // allocate new space
copy(p, p+old_size, temp); // copy old elements over (optional)
swap(p, temp); // swap the pointers, now p refers to the new array
delete [] temp; // deallocate old array
 
// at some point, we need to deallocate memory for the array
 
delete [] p;
 
return 0;
}

null_pointer
null_pointer
Remember that the example I gave you assumes that "new_size" is greater than or equal to "old_size." To wrap this code up into a function we do:

  
// This just makes "T" an alias for whatever type is really used

template <class T>
void redim(T*& array, int old_size, int new_size, bool preserve_old_elements = true)
{
// allocate the new array


T* temp = new T[new_size];

// now copy the elements over, if desired


if( preserve_old_elements )
{
// the number of elements to copy is either the old size or the new size, whichever is smaller


const int elements_to_copy = min(old_size, new_size);

// perform the actual copy


copy(array, array + elements_to_copy, temp);
}

// swap the pointers, so that "array" now points to the new array


swap(array, temp);

// now we need to deallocate the old array


delete [] temp;
}



Edited by - null_pointer on December 31, 2001 3:01:40 PM

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.