创建动态2D数组的一种方法是使用指针数组和动态内存分配。下面是一个示例代码:
#include
int main() {
int rows, cols;
std::cout << "Enter the number of rows: ";
std::cin >> rows;
std::cout << "Enter the number of columns: ";
std::cin >> cols;
// 创建指针数组
int** arr = new int*[rows];
// 分配内存并初始化
for (int i = 0; i < rows; i++) {
arr[i] = new int[cols];
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;
}
这个示例中,我们首先根据用户输入的行数和列数创建了一个指针数组arr
,然后使用循环为每个指针分配内存,最后使用嵌套循环初始化数组的值。打印数组之后,我们使用循环释放了分配的内存。
请注意,为了正确释放内存,我们需要先释放每个指针指向的内存,然后再释放指针数组本身的内存。