c++ allocate and free dynamic 2d array
To allocate and free a dynamic 2D array in C++, you can follow the steps outlined below:
- Allocate memory: To create a dynamic 2D array, you need to allocate memory for the rows and columns.
```cpp int numRows = 3; int numCols = 4;
// Allocate memory for the rows int* array = new int[numRows];
// Allocate memory for the columns in each row for (int i = 0; i < numRows; i++) { array[i] = new int[numCols]; } ```
In this example, we allocate memory for a 2D array with 3 rows and 4 columns. We first allocate memory for the rows using the new
keyword and store the addresses of the allocated memory blocks in array
. Then, we allocate memory for the columns in each row using a loop.
- Access and modify elements: After allocating memory, you can access and modify individual elements of the 2D array using the row and column indices.
cpp
// Access and modify elements
array[0][0] = 1;
array[1][2] = 3;
Here, we access and modify the element at row 0 and column 0 to be 1, and the element at row 1 and column 2 to be 3.
- Free memory: Once you are finished using the dynamic 2D array, you should free the memory to prevent memory leaks.
```cpp // Free memory for the columns in each row for (int i = 0; i < numRows; i++) { delete[] array[i]; }
// Free memory for the rows delete[] array; ```
To free the memory, you need to delete the memory blocks for the columns in each row using the delete[]
keyword in a loop. Then, you can delete the memory blocks for the rows using delete[]
.
By following these steps, you can allocate and free a dynamic 2D array in C++.