Loading lessons...
Dynamically Allocating Arrays
Dynamically Allocating Arrays
Sometimes you don't know how big an array should be until the program runs. That's where arrays on the heap come in.
Allocating with a runtime size
Unlike a fixed array whose size must be known, a heap array can use a size that's only known at runtime:
int size;
cin >> size;
int* arr = new int[size]; // size can come from anywhere
The compiler doesn't need to know size beforehand. This is exactly what a fixed (int nums[5]) can't do.
Resizing the hard way
A fixed array is stuck. To "resize" a heap array, you can allocate a bigger block, copy everything over, and free the old block:
int* bigger = new int[biggerSize];
for (int i = 0; i < size; i++) {
bigger[i] = arr[i]; // copy the old values
}
delete[] arr; // don't leak the old block
arr = bigger;
That's a lot of bookkeeping, and each copy is a chance for bugs.
The zero-filled surprise
Heap arrays are not zero-initialized by default. The default new int[size] leaves values uninitialized - reading them is undefined behavior. Use new int[size]() to value-initialize everything to 0 if that matters.
The modern alternative: std::vector
vector<int> values = {1, 2, 3};
values.push_back(4); // grows automatically, no manual copy
std::vector handles dynamic size, cleanup, and resizing for you. If you need a dynamic array, reach for std::vector first and reserve raw new[] for special cases.
TL;DR
- Heap arrays can use a runtime size:
int* arr = new int[size];. - To resize, you allocate a bigger block, copy the values, and
delete[]the old block. - Match every
new[]with adelete[]when you are done. - Default heap arrays are not zero-initialized.
- Prefer
std::vectorfor dynamic arrays.