C++ (unlike modern C) does not allow you to initialize an array using a value that is computed at run-time. It is possible to do
int x[size];
in C++, but the value contained within size
must be known by the compiler. Therefore, the following is legal
int const size = 10; // Known at compile-time
int x[size];
But the following is not
int size;
cin >> size; // we only know size at run-time
int x[size]; // ERROR!
The reason for this is restriction is technical and I won't go into it here since you're clearly new to the language. Just know that if you want to declare an array (without using the keyword new
) you need to know the size of it at compile-time.
As an alternative, you should check out the container std::vector
, which allows you to safely allocate an array dynamically, without having to use new
and delete
.
std::vector<int> xs(10); // allocate space for ten ints.
The benefit is that, due to vector's destructor, you don't have to worry about managing the memory it allocates, thus leading to safer code.
So, in summary:
- Yes, your understanding of
new
is correct. If you only know the size at run-time, you need dynamic memory. However, avoid using new
if at all possible: prefer vector
.
- C++ simply does not allow arrays to have sizes known at run-time. All arrays created on the stack must have their sizes known at compile-time. This is different than in C, where such a thing is allowed.