two dimensional dynamic array c++
Two-Dimensional Dynamic Array in C++
To create a two-dimensional dynamic array in C++, you can use pointers and dynamic memory allocation. Here are the steps to do it:
- Declare the variables for the number of rows and columns in the array.
- Use the
new
keyword to dynamically allocate memory for the array. - Access the elements of the array using the row and column indices.
- After using the array, deallocate the memory using the
delete
keyword.
Here is an example that demonstrates these steps:
#include <iostream>
int main() {
int rows, cols;
// Get the number of rows and columns from the user
std::cout << "Enter the number of rows: ";
std::cin >> rows;
std::cout << "Enter the number of columns: ";
std::cin >> cols;
// Dynamically allocate memory for the array
int arr = new int*[rows];
for (int i = 0; i < rows; i++) {
arr[i] = new int[cols];
}
// Access and modify the elements of the array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = i + j;
}
}
// Print the elements of the array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
// Deallocate the memory
for (int i = 0; i < rows; i++) {
delete[] arr[i];
}
delete[] arr;
return 0;
}
In this example, the user is prompted to enter the number of rows and columns for the array. The program then dynamically allocates memory for the array using nested loops. The elements of the array are accessed and modified using the row and column indices. Finally, the memory is deallocated using the delete
keyword.
Note: It is important to deallocate the memory allocated for the array to avoid memory leaks.