#include<iostream>
using namespace std;
void func(int (**A)) {
*A = new int[1];
(*A)[0] = 101;
}
void func2(int ***A) {
*A = new int*[1];
(*A)[0] = new int[2]; //维度不确定,一层一层new出来
(*A)[0][0] = 88;
(*A)[0][1] = 77;
}
void func3(int (**A)[2][3]) { //如果多维数组的二三维确定,就可以这样写
*A = new int[1][2][3]; //只需要new一次
(*A)[0][0][1] = 12;
}
int main() {
int (**a) = new (int*);
func(a);
cout<<(*a)[0]<<endl;
delete[] a;
int (***b) = new (int**);
func2(b);
cout<<(*b)[0][0]<<" "<<(*b)[0][1]<<endl;
delete[] *b[0];
delete[] *b;
delete b;
int (**c)[2][3] = new (int (*)[2][3]);
func3(c); //注意不能传空指针进去,传一个指向{指向数组的指针}的指针
cout<<(*c)[0][0][1]<<endl;
delete[] *c;
delete c;
cout<<"********************\n";
//下面是不用函数的多维数组新建
int (*temp2)[2][3];
temp2 = new int[1][2][3]; //数组的第一维如果不确定,二三维都确定,就可以这样写
temp2[0][0][0] = 21;
cout<<temp2[0][0][0]<<endl;
delete[] temp2;
int **temp = new int*[1]; //important! no (int*)[1]
temp[0] = new int[2]; //数组的维数不确定,就可以一层一层new出来
temp[0][0] = 21;
temp[0][1] = 22;
cout<<temp[0][0]<<" "<<temp[0][1]<<endl;
delete[] temp[0];
delete[] temp;
return 0;
}
C++多维数组参数的new
最新推荐文章于 2022-09-04 10:14:13 发布