How to Use new for 2D Array in C++: Syntax and Example
In C++, you can use
new to dynamically allocate a 2D array by first creating an array of pointers and then allocating each row separately with new. This approach allows flexible array sizes at runtime and requires manual deletion to avoid memory leaks.Syntax
To create a dynamic 2D array using new, you first allocate an array of pointers for rows, then allocate each row as an array of elements.
int** arr = new int*[rows];allocates memory for row pointers.- Each row is allocated with
arr[i] = new int[cols];. - Remember to delete each row and then the array of pointers to free memory.
cpp
int** arr = new int*[rows]; for (int i = 0; i < rows; ++i) { arr[i] = new int[cols]; }
Example
This example shows how to create a 3x4 2D array, fill it with values, print them, and then properly free the memory.
cpp
#include <iostream> int main() { int rows = 3; int cols = 4; // Allocate memory for rows int** arr = new int*[rows]; // Allocate memory for each row for (int i = 0; i < rows; ++i) { arr[i] = new int[cols]; } // Fill the array with values for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { arr[i][j] = i * cols + j + 1; } } // Print the array for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << arr[i][j] << ' '; } std::cout << '\n'; } // Free the memory for (int i = 0; i < rows; ++i) { delete[] arr[i]; } delete[] arr; return 0; }
Output
1 2 3 4
5 6 7 8
9 10 11 12
Common Pitfalls
Common mistakes include:
- Not allocating each row separately, which causes undefined behavior.
- Forgetting to delete each row before deleting the array of pointers, leading to memory leaks.
- Mixing
deleteanddelete[]incorrectly.
Always use delete[] for arrays allocated with new[].
cpp
/* Wrong way: single allocation without rows */ int* arr = new int[rows * cols]; // Accessing arr[i][j] is invalid here /* Correct way: allocate rows and columns separately */ int** arr = new int*[rows]; for (int i = 0; i < rows; ++i) { arr[i] = new int[cols]; } // Remember to delete properly for (int i = 0; i < rows; ++i) { delete[] arr[i]; } delete[] arr;
Quick Reference
Tips for using new with 2D arrays:
- Allocate an array of pointers for rows.
- Allocate each row as an array of columns.
- Access elements with
arr[i][j]. - Free memory by deleting each row, then the row pointer array.
- Use
delete[]for arrays allocated withnew[].
Key Takeaways
Use new to allocate an array of pointers for rows, then allocate each row separately.
Always free memory by deleting each row with delete[] before deleting the row pointers.
Access 2D array elements using arr[i][j] after allocation.
Avoid mixing delete and delete[] to prevent undefined behavior.
Dynamic 2D arrays allow flexible sizes but require careful memory management.