动态三维数组分配:
摘自网络
两种方式:
int ***CreateGrid(int hight, int row, int col)
{
int i,j,k;
static 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 p3 ;
}
第二种:
int ***MallocArray3D(int m, int n, int k)
{
static int*** pVariable;
//m element in dimension 1
pVariable=(int***)malloc(sizeof(int**)*m);
for(int i=0;i<m;i++)
{
//n variables for dimension 2
pVariable[i]=(int**)malloc(sizeof(int*)*n);
for(int j=0;j<n;j++)
{
//k variables for dimension 3
pVariable[i][j]=(int*)malloc(sizeof(int)*k);
}
}
return pVariable;
}