如何使用 new 在 C++ 中声明一个二维数组
动态二维数组基本上是数组指针的数组。这是维度为 3 x 4 的二维数组的图表。
算法
Begin Declare dimension of the array. Dynamic allocate 2D array a[][] using new. Fill the array with the elements. Print the array. Clear the memory by deleting it. End
示例代码
#include <iostream> using namespace std; int main() { int B = 4; int A = 5; int** a = new int*[B]; for(int i = 0; i < B; ++i) a[i] = new int[A]; for(int i = 0; i < B; ++i) for(int j = 0; j < A; ++j) a[i][j] = i; for(int i = 0; i < B; ++i) for(int j = 0; j < A; ++j) cout << a[i][j] << "\n"; for(int i = 0; i < A; ++i) delete [] a[i]; delete [] a; return 0; }
输出
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3
广告