Hello to everybody. I am simulating a tree without a recursion, that is I have an array of leaf nodes and I want to go one level deeper. I wrote the following code:
#include <iostream>
using namespace std;
int main()
{
int* row;
int root_row[1];
int row_size = 1;
root_row[0] = 1;
row = root_row;
for (int i = 0; i < 2; i++)
{
int new_row[row_size*4];
for (int k = 0; k < row_size*4; k++)
new_row[k] = -1;
for (int j = 0; j < row_size; j++)
{
int num;
num = row[j]*2;
new_row[j*4] = num;
num = row[j]*3;
new_row[j*4+1] = num;
num = row[j]*4;
new_row[j*4+2] = num;
num = row[j]*5;
new_row[j*4+3] = num;
}
row = new_row;
row_size = row_size*4;
for (int k = 0; k < row_size; k++)
cout << row[k] << " ";
cout << endl;
}
return 0;
}
... which gives unexpected (for me) results:
2 3 4 5
-2 -3 -4 -5 -2 -3 -4 -5 -2 -3 -4 -5 -2 -3 -4 -5
It seems that int new_row[row_size*4];
doesn't create a new array with every iteration. My approach worked well in Java, where array initialization is more explicit: int[] new_row = new int[row_size*4];
. So where am I wrong?