I had this:

classA* class[10];

But now i dont know the exact number(10) and i want to put a variable there and i get a compilation error.What i should do instead?

Recommended Answers

All 2 Replies

C++ doesn't support non-constant array sizes. You need to simulate an array with a pointer and dynamic memory:

// Simulate an array of pointers to classA
classA **array = new classA*[size];

// Populate the elements
for ( int i = 0; i < size; i++ )
  array[i] = new classA();

// Use the array...

// Release the elements
for ( int i = 0; i < size; i++ )
  delete array[i];

// Release the simulated array
delete[] array;

>> You need to simulate an array with a pointer and dynamic memory

Better yet, you should use the standard containers. Depending on your
situation, certain one will be better suited. But Below I will give an
example of how to use std::vector to simulate a variable sized array.

#include <iostream>
#include <vector>

using namespace std;


struct CTest{
	CTest(int i = 0)
	{
		static size_t cnt = 0;
		cout <<"Class # " << (++cnt) << " with value : " << i << endl;		
	}	
};
int main ()
{
	vector<CTest> Array;

	int size = 0;
	
	cout<<"Enter size : ";
	
	cin >> size;
	
	//resize the size to what the user enters.
	Array.resize( size , CTest(1) ); //Prints Class # 1 with value 1

	//iterate over the array
	for(int i = 0; i < Array.size(); ++i)
		Array[i] = CTest(10+i);/* do stuff */ //Prints Class # (2+i) with value (10+i)

	//no need to delete  the vector;
	
	return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.