How to dynamically create a two-dimensional array in C+…
In C++, you can dynamically create a two-dimensional array using pointers and dynamic memory allocation. Here is an example:
#include <iostream>
int main() {
int rows, cols;
std::cout << "请输入行数和列数:";
std::cin >> rows >> cols;
// 动态分配内存
int** arr = new int*[rows];
for (int i = 0; i < rows; i++) {
arr[i] = new int[cols];
}
// 初始化二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = i * cols + j;
}
}
// 打印二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
// 释放内存
for (int i = 0; i < rows; i++) {
delete[] arr[i];
}
delete[] arr;
return 0;
}
In this example, first, obtain the number of rows and columns for the two-dimensional array to be created from the user. Then, use the new operator to dynamically allocate memory to store row pointers. Next, use loops to allocate memory for each row to store column data. Then, the two-dimensional array can be initialized and accessed using loops as needed. Finally, remember to release the dynamically allocated memory after using the two-dimensional array to prevent memory leaks.