Moshe Moshe - 11 months ago 36
C++ Question

Is it possible to allow a user to enter an array size with a keyboard?

Is it possible to allow the user to enter the size of an array with a keyboard?

I know that arrays can't change size. The only solution I could think of is this:

int userSize;

cin >> userSize;

const int SIZE = userSize;

int array[SIZE];


How can I verify that this works? Should I use a vector instead?

Answer Source

Variable Length Arrays are not approved by C++ standard. C++ Standard mandates that the size of an array must be an compile time constant.
You can use VLA's through compiler extension provided in gcc but note the your code is not portable if you do so.

Standard approved way of doing this is to use std::vector.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download