仅供参考:
#include <stdio.h>
#include <stdlib.h>
int ***newarr3d(int lays,int rows,int cols) {
int ***p,z,r;
p=new int **[lays];
for (z=0;z<lays;z++) {
p[z]=new int*[rows];
for (r=0;r<rows;r++) {
p[z][r]=new int[cols];
}
}
return p;
}
void deletearr3d(int ***p,int lays,int rows) {
int z,r;
for (z=0;z<lays;z++) {
for (r=0;r<rows;r++) {
delete[] p[z][r];
}
delete[] p[z];
}
delete[] p;
}
int main() {
int ***arr3d,z,r,c,lays,rows,cols;
lays=3;
rows=4;
cols=5;
//在堆中开辟一个3×4×5的三维int数组
arr3d=newarr3d(lays,rows,cols);
for (z=0;z<lays;z++) {
for (r=0;r<rows;r++) {
for (c=0;c<cols;c++) {
arr3d[z][r][c]=z*rows*cols+r*cols+c;
}
}
}
for (z=0;z<lays;z++) {
for (r=0;r<rows;r++) {
for (c=0;c<cols;c++) {
printf(" %2d",arr3d[z][r][c]);
}
printf("\n");
}
printf("---------------\n");
}
printf("======================\n");
deletearr3d(arr3d,lays,rows);
lays=2;
rows=6;
cols=3;
//在堆中开辟一个2×6×3的三维int数组
arr3d=newarr3d(lays,rows,cols);
for (z=0;z<lays;z++) {
for (r=0;r<rows;r++) {
for (c=0;c<cols;c++) {
arr3d[z][r][c]=z*rows*cols+r*cols+c;
}
}
}
for (z=0;z<lays;z++) {
for (r=0;r<rows;r++) {
for (c=0;c<cols;c++) {
printf(" %2d",arr3d[z][r][c]);
}
printf("\n");
}
printf("---------------\n");
}
printf("======================\n");
deletearr3d(arr3d,lays,rows);
return 0;
}
// 0 1 2 3 4
// 5 6 7 8 9
// 10 11 12 13 14
// 15 16 17 18 19
//---------------
// 20 21 22 23 24
// 25 26 27 28 29
// 30 31 32 33 34
// 35 36 37 38 39
//---------------
// 40 41 42 43 44
// 45 46 47 48 49
// 50 51 52 53 54
// 55 56 57 58 59
//---------------
//======================
// 0 1 2
// 3 4 5
// 6 7 8
// 9 10 11
// 12 13 14
// 15 16 17
//---------------
// 18 19 20
// 21 22 23
// 24 25 26
// 27 28 29
// 30 31 32
// 33 34 35
//---------------
//======================
//