如何在C++中实现网格的动态调整
导读:在C++中实现网格(二维数组)的动态调整,可以使用指针和动态内存分配 #include<iostream> int main( { int rows, cols; std::cout << "E...
在C++中实现网格(二维数组)的动态调整,可以使用指针和动态内存分配
#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;
// 使用new操作符为二维数组分配内存
int** grid = new int*[rows];
for (int i = 0;
i<
rows;
++i) {
grid[i] = new int[cols];
}
// 填充网格
for (int i = 0;
i<
rows;
++i) {
for (int j = 0;
j<
cols;
++j) {
std::cout <
<
"Enter the value for grid[" <
<
i <
<
"][" <
<
j <
<
"]: ";
std::cin >
>
grid[i][j];
}
}
// 打印网格
std::cout <
<
"The grid is: "<
<
std::endl;
for (int i = 0;
i<
rows;
++i) {
for (int j = 0;
j<
cols;
++j) {
std::cout<
<
grid[i][j] <
<
" ";
}
std::cout<
<
std::endl;
}
// 使用delete操作符释放内存
for (int i = 0;
i<
rows;
++i) {
delete[] grid[i];
}
delete[] grid;
return 0;
}
这个程序首先接收用户输入的行数和列数,然后使用new
操作符为二维数组分配内存。接下来,程序填充网格并将其打印出来。最后,使用delete
操作符释放分配的内存。
注意:在使用动态内存分配时,一定要确保在不再需要内存时释放它,以避免内存泄漏。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何在C++中实现网格的动态调整
本文地址: https://pptw.com/jishu/699298.html