I want to create a C++ dynamic array of integers using the new keyword. What is the correct syntax to allocate, use, and eventually free a dynamic integer array in C++?
I’ve done this many times
. In C++, you can allocate a dynamic array like this:
#include <iostream>
int main() {
int n = 5;
// Allocate dynamic array
int* arr = new int[n];
// Use the array
for (int i = 0; i < n; ++i) {
arr[i] = i * 10;
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// Free memory
delete[] arr;
return 0;
}
Always pair new[] with delete[] to avoid memory leaks.
I use this when I need manual control over array size at runtime.
Honestly, I almost always prefer std::vector now:
#include <iostream>
#include <vector>
int main() {
int n = 5;
std::vector<int> arr(n); // dynamic size
for (int i = 0; i < n; ++i) {
arr[i] = i * 10;
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// No need to manually delete—vector cleans up automatically
return 0;
}
std::vector handles memory management automatically.
You can resize it anytime with arr.push_back(value), much safer and more flexible than raw pointers.
For modern C++ (C++11+), you can use std::unique_ptr for automatic cleanup:
#include <iostream>
#include <memory>
int main() {
int n = 5;
std::unique_ptr<int[]> arr(new int[n]);
for (int i = 0; i < n; ++i) {
arr[i] = i * 10;
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// Memory is automatically freed when arr goes out of scope
return 0;
}
I use this when I need raw-style arrays but want automatic memory management.
Combines safety of vector with familiar array syntax.