阅读量:81
在C ++中,可以使用指针和new关键字来定义动态二维数组。以下是一个示例:
int rows = 3; // 二维数组的行数
int cols = 4; // 二维数组的列数
// 分配内存
int **arr = new int*[rows];
for (int i = 0; i < rows xss=removed class="hljs-keyword">new int[cols];
}
// 初始化数组
for (int i = 0; i < rows class="hljs-keyword">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;
在上面的示例中,我们首先使用new关键字分配动态二维数组的内存,然后使用双重循环对数组进行初始化和访问。最后,我们使用delete[]释放内存。请注意,释放内存的顺序应该与分配内存的顺序相反。