# 如何用new来创建二维数组

#### 方法1：指针的指针

int R = 2;
int C = 3;
auto ptr_2d = new A*[R]; //先new一个A*类型的“数组”
for (int i = 0; i < R; i++) {
ptr_2d[i] = new A[C]; //每个int*再指向一个A类型的“数组”
}
cout << "Type of ptr_2d: " << typeid(ptr_2d).name() << endl; //输出PP1A
cout << "Type of ptr_2d[0]: " << typeid(ptr_2d[0]).name() << endl; //输出P1A


Constructing A...
Constructing A...
Constructing A...
Constructing A...
Constructing A...
Constructing A...
Type of ptr_2d: PP1A
Type of ptr_2d[0]: P1A


for (int i = 0; i < R; i++)
delete[] ptr_2d[i];
delete[] ptr_2d;


Deleting A...
Deleting A...
Deleting A...
Deleting A...
Deleting A...
Deleting A...


int R = 2;
int C = 3;
auto ptr_2d = new A*[R];
for (int i = 0; i < R; i++) {
ptr_2d[i] = new A[C];
}
auto last_ptr = &(ptr_2d[0][0]);
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++) {
if ((i || j) && last_ptr + 1 != &(ptr_2d[i][j])) {
cout << "Incontiguous memory between ptr_2d[" << i << "][" << j
<< "] (" << &(ptr_2d[i][j]) << ") and last_ptr ("
<< last_ptr << ")" << endl;
}
last_ptr = &(ptr_2d[i][j]);
}


#### 方法2：数组的指针

int R = 2;
const int C = 3; //如果这里是int C = 3就不行了。
auto ptr_2d = new A[R][C]; //当然，也可以是new A[R][3]，3也是常量
cout << "Type of ptr_2d: " << typeid(ptr_2d).name() << endl;
cout << "Type of ptr_2d[0]: " << typeid(ptr_2d[0]).name() << endl;
//do something...
delete[] ptr_2d;


Constructing A...
Constructing A...
Constructing A...
Constructing A...
Constructing A...
Constructing A...
Type of ptr_2d: PA3_1A
Type of ptr_2d[0]: A3_1A
Deleting A...
Deleting A...
Deleting A...
Deleting A...
Deleting A...
Deleting A...


posted @ 2021-04-04 20:05  胡小兔  阅读(86)  评论(0编辑  收藏