如题所述
给你一个三维的例子:
int nx = 10; //行数
int ny = 10; //列数
int nz = 10; //层数
int*** arr_np3D = NULL;
//创建
//分配第一层
arr_np3D = (int***)new int**[nz];
//分配第二层
for (int i=0; i<ny; i++)
{
arr_np3D[i] = (int**)new int*[ny];
}
//分配第三层
for (int i=0; i<ny; i++)
{
for (int j=0; j<nx; j++)
{
arr_np3D[i][j] = new int[nx];
}
}
//访问元素
arr_np3D[2][5][4] = 10;
cout<<arr_np3D[2][5][4];
//释放
//释放第三层
for (int i=0; i<ny; i++)
{
for (int j=0; j<nx; j++)
{
delete[] arr_np3D[i][j];
arr_np3D[i][j] = NULL;
}
}
//释放第二层
for (int i=0; i<ny; i++)
{
delete[] arr_np3D[i];
arr_np3D[i] = NULL;
}
//释放第一层
delete[] arr_np3D;
arr_np3D = NULL;
int nx = 10; //行数
int ny = 10; //列数
int nz = 10; //层数
int*** arr_np3D = NULL;
//创建
//分配第一层
arr_np3D = (int***)new int**[nz];
//分配第二层
for (int i=0; i<ny; i++)
{
arr_np3D[i] = (int**)new int*[ny];
}
//分配第三层
for (int i=0; i<ny; i++)
{
for (int j=0; j<nx; j++)
{
arr_np3D[i][j] = new int[nx];
}
}
//访问元素
arr_np3D[2][5][4] = 10;
cout<<arr_np3D[2][5][4];
//释放
//释放第三层
for (int i=0; i<ny; i++)
{
for (int j=0; j<nx; j++)
{
delete[] arr_np3D[i][j];
arr_np3D[i][j] = NULL;
}
}
//释放第二层
for (int i=0; i<ny; i++)
{
delete[] arr_np3D[i];
arr_np3D[i] = NULL;
}
//释放第一层
delete[] arr_np3D;
arr_np3D = NULL;
温馨提示:答案为网友推荐,仅供参考