C++中動態定義一維陣列,二維陣列,三維陣列
阿新 • • 發佈:2018-12-30
//動態定義一維陣列、二維陣列、三維陣列 #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 ; }
vc6.0下面的程式碼會出錯
int rows=10;
int columns=10;
double count=0;
double **p=(double **)malloc(sizeof(*p )*rows);
for (int j=0;j<rows;j++)
{
p[j]=(double *)malloc(sizeof(**p)*columns);
}