0

I would like to know is possible to create arrays as user requires. For example

  1. I ask the user "Do you want coffee" 2.if the user say yes and i create a array of coffee object. .....
  2. I ask the user "Do you want to have another coffee"?
  3. if user say yes than i create another array of coffee class if not i dont create.

Is this achieveable or must i create a fixed number of array?

0

2 Answers 2

2

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;.

Sign up to request clarification or add additional context in comments.

4 Comments

int * myArray = new int[5]; // creating a fixed-size array at runtime in C++?
@JeremyFriesner, no that's not fixed sized array. It's a dynamic array similar to std::vector; only syntactical difference is that new[] returns a raw pointer. Internally std::vector does new[] and lot more things.
I cant use vector. I need to use array only.
@iammilind can u explain abit further, sample codes may be please.
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.