This is part of a larger code I'm working on but I've trimmed it down and simplified it to show the problem I'm having. The entries in the arrays in this example are not the same as the ones in my actual code, here it's just for illustration.
The idea behind the code is this:
Initially create an array called array1 which has 1 and 2 contained in it
.
At each stage of the loop (i=3 to i=length), delcare a new array called array2.
Fill array2 with the values in array1 then make the last value in array2 equal to i.
We now delete array1 and create a new array1 of size i.
Make this have the same entries as array2.
delete array2.
So it should go something like...
array1 = {1, 2};
array2 = {1, 2, 3};
delete array1.
new array1 = {1, 2, 3}.
delete array2.
Repeat using same 'fill and add an additional entry' method with a new array1.
Now at the beginning and end of the loop I output the entries in array1 just to see it's all working. When i=3, the output at the end is {1,2,3} as expected. When I then output the entries of array1 at the beginning of i=4, I expect it to again be 1,2,3 but it shows up as {0,2,131074}! Since I haven't done anything to array1 between these two ouputs, I'm not sure why this happens. I imagine this stems from my lack of understanding of how pointers work or perhaps the new/delete commands but maybe it's just a stupid error somewhere...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
using namespace std;
int main()
{
int length = 4;
int *array1 = new int [2];
array1[0] = 1;
array1[1] = 2;
for (int i = 3; i <= length; i++)
{
for (int j = 0; j < i-1; j++)
{
cout << array1[j] << " ";
}
cout << endl;
int *array2 = new int [i];
for (int k = 0; k < i-1; k++)
{
array2[k] = array1[k];
}
array2[i-1] = i;
delete[] array1;
int *array1 = new int [i];
for (int p = 0; p < i; p++)
{
array1[p] = array2[p];
}
delete[] array2;
for (int jj = 0; jj < i; jj++)
{
cout << array1[jj] << " ";
}
cout << endl;
}
return 0;
}
|