How to Allocate Array Dynamically in C++: Syntax and Examples
In C++, you allocate an array dynamically using the
new operator like int* arr = new int[size];. Remember to free the memory with delete[] arr; to avoid memory leaks.Syntax
To allocate an array dynamically in C++, use the new operator followed by the type and size in brackets. To free the memory, use delete[] with the pointer.
- new Type[size]: Allocates an array of
sizeelements ofType. - delete[] pointer: Frees the memory allocated for the array.
cpp
Type* pointer = new Type[size]; // Use the array delete[] pointer;
Example
This example shows how to allocate an integer array dynamically, assign values, print them, and then free the memory.
cpp
#include <iostream> int main() { int size = 5; int* arr = new int[size]; // allocate array dynamically for (int i = 0; i < size; ++i) { arr[i] = (i + 1) * 10; // assign values } for (int i = 0; i < size; ++i) { std::cout << arr[i] << " "; // print values } std::cout << std::endl; delete[] arr; // free memory return 0; }
Output
10 20 30 40 50
Common Pitfalls
Common mistakes when allocating arrays dynamically include:
- Forgetting to use
delete[]to free memory, causing memory leaks. - Using
deleteinstead ofdelete[]for arrays, which leads to undefined behavior. - Accessing out-of-bounds indices, which causes runtime errors.
cpp
#include <iostream> int main() { int size = 3; int* arr = new int[size]; // Wrong: Using delete instead of delete[] // delete arr; // Incorrect for arrays // Correct way: delete[] arr; return 0; }
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Allocate array | Type* ptr = new Type[size]; | Creates a dynamic array of given size. |
| Access element | ptr[index] | Access element at position index. |
| Free array | delete[] ptr; | Frees the allocated memory for the array. |
Key Takeaways
Use
new Type[size] to allocate arrays dynamically in C++.Always free dynamic arrays with
delete[] to avoid memory leaks.Do not use
delete without brackets for arrays; it causes undefined behavior.Check array bounds to prevent runtime errors.
Dynamic arrays allow flexible size allocation at runtime.