Dynamic arrays

Say I have an array with 5 "indexes":

int array[5];


How can I turn that into a [6] array later in the program without deleting what is already stored in the array?
you can't do that since

int array[5];

is allocated on the stack

your best option would be to use a STL vector for your array, that way you can change the size as you want:

1
2
3
4
5
std::vector<int> array(5);

array[1] = 1;

array.push_back(123); // added a sixth element. 


A second option would be a combination of malloc() and realloc(), but I'd recommend std::vectors, too.
You need to start off allocating your array dynamically.

1
2
int size = 5;
int* array = new int[size];


then when you want to increase it:

1
2
3
4
5
6
7
8
9
int* array2 = new int[size];
for (int i = 0; i < size; ++i)
  array2[i] = array[i];
delete[] array;
++size;
array = new int[size];
for (int i = 0; i < size - 1; ++i)
  array[i] = array2[i];
delete[] array2;


now you have the original 5 values (array[0] - array[4]) and a new array[5] position to work with.

~psault
Topic archived. No new replies allowed.