We already did dynamically allocating memory for scalar types in introduction to dynamic allocation. This note describes about allocating memory to array dynamically.
Commonly, we use C-style arrays to create arrays dynamically. We could use std::array but we have a better choice for dynamic arrays as std::vector.
Allocation using new[]
For dynamic allocation for arrays, C++ has same new operator but with slight change. Here, we use new[] operator to differentiate the allocation for array. For example:
int *arr{new int[5]{}};Although we are not using [] with new, compiler still understands new[] form.
We can also provide initializer values as:
int *arr{new int[5]{1, 2, 3, 4, 5}};Here, the length specified in [] does not have to be a constexpr value like C-style array or std::array. For example:
std::size_t length{};
std::cin >> length;
int *arr{new int[length]{}};Deallocation using delete[]
Similar to new form for new[] for arrays, delete also has new form delete[] which let’s compiler know its going to deallocate memory for array.
For example:
delete[] arr;