C++ Dynamic Arrays
In this page:
Allocating Dynamic Arrays
A dynamic array is allocated on the heap with new[] at runtime, which means its size can be a variable computed while the program is running, unlike a fixed-size stack array whose length must be a compile-time constant. This makes it the right choice whenever you don't know how much data you'll need to store until later.
Example: Allocating Dynamic Arrays
#include <iostream>
int main() {
int size = 5;
int *arr = new int[size];
std::cout << "Allocated " << size << " ints" << std::endl;
delete[] arr;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Initializing Dynamic Arrays
You can fill a dynamic array element-by-element in a loop after allocation, or use value initialization -- new int[n]() with the trailing parentheses -- to zero-initialize every element automatically instead of leaving them with unpredictable garbage values.
Example: Initializing Dynamic Arrays
#include <iostream>
int main() {
int *arr = new int[3]();
std::cout << arr[0] << " " << arr[1] << " " << arr[2] << std::endl;
delete[] arr;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing and Modifying
Once allocated, a dynamic array is accessed with the same arr[i] syntax as a stack array, since the pointer new[] returns behaves like the array's name. Internally that pointer just stores the memory address of the first element, and indexing computes an offset from it.
Example: Accessing and Modifying
#include <iostream>
int main() {
int *arr = new int[3];
arr[0] = 10;
arr[1] = 20;
std::cout << arr[0] << " " << arr[1] << std::endl;
delete[] arr;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Deallocating Dynamic Arrays
delete[] must be called exactly once on a dynamic array when you're done with it, or the heap memory it occupies is never returned to the system. Setting the pointer to nullptr afterward is good practice so any accidental later use is caught rather than silently corrupting memory.
Example: Deallocating Dynamic Arrays
#include <iostream>
int main() {
int *arr = new int[3]{1, 2, 3};
delete[] arr;
arr = nullptr;
std::cout << "Freed" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Resizing Dynamic Arrays
C++ arrays can't grow or shrink in place -- to "resize" one, you allocate a new, larger array, copy the existing elements into it, and delete the old array. This copy-and-replace pattern is exactly what std::vector automates internally, which is why vector is usually preferred over manual dynamic arrays.
Example: Resizing Dynamic Arrays
#include <iostream>
int main() {
int *arr = new int[2]{1, 2};
int *bigger = new int[4];
for (int i = 0; i < 2; i++) bigger[i] = arr[i];
delete[] arr;
arr = bigger;
std::cout << arr[0] << " " << arr[1] << std::endl;
delete[] arr;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: