C++ 实现动态定义三维内的数组
//动态定义一维数组、二维数组、三维数组
#include<iostream>
#include<ctime>
using namespace std ;
int main()
{
int hight , row , col ;
register int i , j , k ;
srand((unsigned)time(NULL)) ;
cout<<"输入一维数组的行"<<endl;
cin>>row ;
//动态定义一维数组
int *p1 ;
p1 = new int [row] ;
//输入一维数组的值
for( i = 0 ; i < row ; i ++ )
p1[i] = rand () % 10 ;
//输出一维数组
for( i = 0 ; i < row ; i ++ )
cout<<p1[i] <<' ' ;
cout<<endl;
//释放一维数组
delete [] p1 ;
cout<<"输入二维数组的行,列 :";
cin>>row >>col ;
//动态定义二维数组
int **p2 ;
p2 = new int*[row] ;
for( i = 0 ; i < row ; i ++ )
p2[i] = new int[col] ;
//输入二维数组的值
for( i = 0 ; i < row ; i ++ )
for( j = 0 ; j < col ; j ++ )
p2[i][j] = rand() % 10 ;
//输出二维数组
cout<<"输出二位数组:"<<endl;
for( i = 0 ; i < row ; i ++ )
{
for( j = 0 ;j < col ; j ++ )
cout<<p2[i][j]<<' ' ;
cout<<endl;
}
//释放二维数组
for( i = 0 ; i < row ; i ++ )
delete []p2[i] ;
delete []p2 ;
cout<<"输入三维数组高,行,列 : ";
cin>>hight>>row >> col ;
//动态定义三维数组:
int *** p3 ;
p3 = new int**[hight ] ;
for( i = 0 ; i < hight ; i ++ )
p3[i] = new int*[row] ;
for( i = 0 ; i < hight ; i ++ )
for( j = 0 ; j < row ; j ++ )
p3[i][j] = new int[col] ;
//输入三维数组值:
for(i = 0 ; i < hight ; i ++ )
for(j = 0 ; j < row ; j ++ )
for( k = 0 ; k < col ; k ++)
p3[i][j][k] = rand()%10 ;
//输出三维数组:
cout<<"输出三维数组"<<endl;
for(i = 0 ; i < hight ; i ++ )
{
for( j = 0 ; j < row ; j ++ )
{
for( k = 0 ; k < col ; k ++ )
cout<<p3[i][j][k]<<' ' ;
cout<<endl;
}
cout<<endl;
}
//释放三维数组
for( i = 0 ; i < hight ; i ++ )
for( j = 0 ; j < row ; j ++ )
delete []p3[i][j] ;
for( i = 0 ; i < hight ; i ++ )
delete []p3[i] ;
delete []p3 ;
return 0 ;
}