In addition to dynamically allocating single values, we can also dynamically allocate arrays of variables. Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime (meaning our length does not need to be constexpr).
Author’s note
In these lessons, we’ll be dynamically allocating C-style arrays, which is the most common type of dynamically allocated array.
While you can dynamically allocate a std::array, you’re usually better off using a non-dynamically allocated std::vector in this case.
To allocate an array dynamically, we use the array form of new and delete (often called new[] and delete[]):
#include <cstddef>
#include <iostream>
int main()
{
std::cout << "Enter a positive integer: ";
std::size_t length{};
std::cin >> length;
int* array{ new int[length]{} }; // use array new. Note that length does not need to be constant!
std::cout << "I just allocated an array of integers of length " << length << '\n';
array[0] = 5; // set element 0 to value 5
delete[] array; // use array delete to deallocate array
// we don't need to set array to nullptr/0 here because it's going out of scope immediately after this anyway
return 0;
}
Because we are allocating an array, C++ knows that it should use the array version of new instead of the scalar version of new. Essentially, the new[] operator is called, even though the [] isn’t placed next to the new keyword.
The length of dynamically allocated arrays has type std::size_t. If you are using a non-constexpr int, you’ll need to
