C++ : Creating an array with a size entered by the user

arrays, c++

Solution

In C++, there are two types of storage: stack-based memory, and heap-based memory. The size of an object in stack-based memory must be static (i.e. not changing), and therefore must be known at compile time. That means you can do this:

int array[10]; // fine, size of array known to be 10 at compile time

but not this:

int size;
// set size at runtime
int array[size]; // error, what is the size of array?

Note there is a difference between a constant value and a value known at compile time, which means you can't even do this:

int i;
// set i at runtime
const int size = i;
int array[size]; // error, size not known at compile time

If you want a dynamically-sized object, you can access heap-based memory with some form of the `new` operator:

int size;
// set size at runtime
int* array = new int[size] // fine, size of array can be determined at runtime

However, this 'raw' usage of `new` is not recommended as you must use `delete` to recover the allocated memory.

delete[] array;

This is a pain, as you have to remember to `delete` everything you create with `new` (and only `delete` once). Fortunately, C++ has many data structures that do this for you (i.e. they use `new` and `delete` behind the scenes to dynamically change the size of the object).

`std::vector` is one example of these self-managing data structures, and is a direct replacement for an array. That means you can do this:

int size;
// set size at runtime
std::vector<int> vec(size); // fine, size of vector can be set at runtime

and don't have to worry about `new` or `delete`. It gets even better, because `std::vector` will automatically resize itself as you add more elements.

vec.push_back(0); // fine, std::vector will request more memory if needed

In summary: don't use arrays unless you know the size at compile time (in which case, don't use `new`), instead use `std::vector`.

Problem

I was wondering if we can make an array with a size specified by the user. Ex: ``` int a; cout<<"Enter desired size of the array"; cin>>a; int array[a]; ``` The above program won't work as array size has to be a compile-time constant but in my case, it is a variable. Is it possible to make a variable into a constant and assign it as size of an array?

Original source