Reputation: 115
I would like to know is possible to create arrays as user requires. For example
Is this achieveable or must i create a fixed number of array?
Upvotes: 0
Views: 118
Reputation: 69998
You cannot create fixed size array at runtime in C++, except some compilers (like g++) provides extension for VLA.
Use std::vector
instead. It grows as per your control and automatically deallocates itself when requirement is done.
Edit: As the std::vector
cannot be used by the asker, following is the way using new[]
with 'some' pseudo code:
Coffee **pQuestions = new Coffee* [n]; // n - number of times coffee is asked
for(uint i = 0; i < N; ++i)
{
/* ask for Coffee */
if(/* yes */)
pQuestion[i] = new Coffee[size]; // whatever array size you want
}
Here n
and size
are variables(can or cannot be constants) as per your need
Later when you are done, deallocate all the memory as delete[] pQuestions[i];
and delete[] pQuestions;
.
Upvotes: 2
Reputation: 1
You can use standard container classes like std::vector which gives you resizeable vectors of some arbitrary but given type. Of course, you can have vectors of vectors, or vectors of queues, etc.
(You could use manually allocated pointers and code à la C, but you'll better use the powerful containers provided by the STL).
Upvotes: 0