阅读量:80
在C++中,动态二维数组通常使用指针数组来实现。如果我们有一个动态二维数组arr,可以使用以下方法来遍历它:
int rows = 3; // 假设数组有3行
int cols = 4; // 假设数组有4列
// 分配内存并初始化数组
int** arr = new int*[rows];
for (int i = 0; i < rows xss=removed class="hljs-keyword">new int[cols];
for (int j = 0; j < cols xss=removed class="hljs-comment">// 遍历数组
for (int i = 0; i < rows class="hljs-keyword">for (int j = 0; j < cols class="hljs-string">" ";
}
std::cout << std class="hljs-comment">// 释放内存
for (int i = 0; i < rows class="hljs-keyword">delete[] arr[i];
}
delete[] arr;
这段代码首先分配内存并初始化一个3行4列的二维数组arr,然后使用两个嵌套的循环遍历数组的每个元素,并输出到控制台。最后,记得释放内存以避免内存泄漏。