c++ 动态创建二维数组
时间: 2024-09-09 18:11:20 浏览: 59
在 C++ 中,动态创建二维数组通常使用 `new` 关键字来分配内存空间,因为数组大小在运行时才确定。下面是一个简单的示例,展示如何动态创建一个行数和列数可变的二维整型数组:
```cpp
#include <iostream>
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** dynamicArray = new int*[rows]; // 创建行指针数组
for (int i = 0; i < rows; ++i) {
dynamicArray[i] = new int[cols]; // 对于每行,创建列数据
}
// 使用动态数组(例如,设置一些元素)
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
dynamicArray[i][j] = i * cols + j; // 只是为了演示,实际应用可能有不同的值
std::cout << dynamicArray[i][j] << ' ';
}
std::cout << '\n';
}
// 释放内存
for (int i = 0; i < rows; ++i) {
delete[] dynamicArray[i]; // 每一行
}
delete[] dynamicArray; // 主数组
return 0;
}
```
在这个例子中,程序首先根据用户的输入获取行数和列数,然后分别对每一行分配内存并存储元素。最后,在完成操作后,通过 `delete[]` 来逐行释放内存,并最终释放整个主数组。
阅读全文
相关推荐
















