Dynamic array that can be re-sized at runtime

hi

how can I create a dynamic array that can be re-sized at run time.

The code below is part of a while loop that has to add new data when its found but the problem I'm having is that its resetting all the array's elements after every cycle. And I'm thinking the new declaration might be the result.

any advice on adding stuff within my loop.

plus I'm also having trouble deleting the run time arrays afterwards,,
1
2
3
4
5
6
7
	if (sGetInput == "O3")
{
	adThirdOrbit = new double[ielemnts3];
			FI_ZumaLv1 >> adThirdOrbit[ielemnts3];
			ielemnts3++;
			FI_ZumaLv1 >> adThirdOrbit[ielemnts3];
			ielemnts3++;


...
/*assertion error is here, but maybe its due to the error in the dynamic array above*/
delete[] adThirdOrbit; //store third orbit in array
}
Last edited on
1. An array of size N has elems from 0 .. N-1. So you are setting values beyond the end of your array's memory space. This is probably what the assert is about (you don't provide the assert statement).

2. Every time you call new you are allocating a new array. So if you are calling new inside a loop and delete just once, outside of the loop, then you are leaking memory for all new calls save for the last one.

3. new cannot be used to resize an array. If you need to resize an array, you need to allocate a new one, then copy all the data from the old one, and then delete the old one.

4. If you are not doing this an exercise in managing memory using new/delete, you should consider using std::vector.
Last edited on
Topic archived. No new replies allowed.