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?

java is oop language based so every thing is declared using class and poiters

in c++ you can use pointers to crate dynamic array like that

int size=0;
cin>>size;
int* dynamicarray=new int[size];

i hope that i helped you

this is not a valid c++ program (size of a c-style array must be a constant known at compile time).

int main()
{
   // ...
   int row_size = 1 ;
   // ...
   int new_row[row_size*4] ; // error: ISO C++ forbids 
                  // variable-size array 'new_row'
   // ...
}

this is (size of a vector<> can be decided at run time).

#include <vector>
int main()
{
   // ...
   int row_size = 1 ;
   // ...
   std::vector<int> new_row(row_size*4) ; // fine
   // ...
}

use a vector instead, it behaves like a resizable java array with value semantics.

This article has been dead for over six months. Start a new discussion instead.