如何在vc中创建动态数组
发布网友
发布时间:2022-05-14 08:35
我来回答
共1个回答
热心网友
时间:2023-10-11 16:43
int n1, n2;
const int DIM1 = 2;
const int DIM2 = 3;
// 构造数组
int **ppi = new int*[DIM1];
for(n1 = 0; n1 < DIM1; n1++){ppi[n1] = new int[DIM2];}// 填充数据
for(n1 = 0; n1 < DIM1; n1++){for(n2 = 0; n2 < DIM2; n2++){ppi[n1][n2] = n1 * 10 + n2;}}// 输出for(n1 = 0; n1 < DIM1; n1++){for(n2 = 0; n2 < DIM2; n2++){afxDump << "ppi[" << n1 << "][" << n2 << "] = "
<< ppi[n1][n2] << "\n";}}// 释放数组
for(n1 = 0; n1 < DIM1; n1++){delete [] ppi[n1];}delete [] ppi;
2. 三维动态数组(int[2][3][4])
///////////////////////////////////////////////////////////////////
int n1, n2, n3;
const int DIM1 = 2;
const int DIM2 = 3;
const int DIM3 = 4;
// 构造数组
int ***ppi = new int**[DIM1];
for(n1 = 0; n1 < DIM1; n1++){ppi[n1] = new int*[DIM2];
for(n2 = 0; n2 < DIM2; n2++){ppi[n1][n2] = new int[DIM3];}}// 填充数据
for(n1 = 0; n1 < DIM1; n1++){for(n2 = 0; n2 < DIM2; n2++){for(n3 = 0; n3 < DIM3; n3++){ppi[n1][n2][n3] = n1 * 100 + n2 * 10 + n3;}}}// 输出for(n1 = 0; n1 < DIM1; n1++){for(n2 = 0; n2 < DIM2; n2++){for(n3 = 0; n3 < DIM3; n3++){afxDump << "ppi[" << n1 << "][" << n2 << "][" << n3 << "] = "
<< ppi[n1][n2][n3] << "\n";}}}// 释放数组
for(n1 = 0; n1 < DIM1; n1++){for(n2 = 0; n2 < DIM2; n2++){delete [] ppi[n1][n2];}delete [] ppi[n1];}delete [] ppi;
如果是一维的,
int *arr; //可以是其它类型 (char, float...)
arr = new int[n]; //n 必须是整型变量
二维的呢,这样来,
int **arr;int n,m;cin n m;arr = new int*[n];上面的代码就可以通过动态输入n,m来实现二维数组的定义