C++动态多维数组范例
//creation of dynamic multidimensional arrays? #include <iostream> #include <iomanip> using namespace std; int main() { //For creating one dimension array of 4 integers int *ptr1; ptr1 = new int[4]; for( int i = 0 ; i < 4 ; i++) { ptr1[i] = i+1; } cout << "\nOne dimension array of 4 integers:\n"; for( int i = 0 ; i < 4 ; i++) { cout << " " << ptr1[i] ; } cout << endl << endl; //for creating two dimensional array of 3 by 4 integers int **ptr2; ptr2 = new int*[3]; for( int i = 0 ; i < 3 ; i++) { ptr2[i] = new int[4]; } for( int i = 0 ; i < 3 ; i++) { for ( int j = 0 ; j < 4 ; j++) { ptr2[i][j] = i * 4 + j; } } cout << "\nTwo dimensions array of 3 by 4 integers:\n"; for( int i = 0 ; i < 3 ; i++) { for ( int j = 0 ; j < 4 ; j++) { cout << setw(4) << right << ptr2[i][j] << " "; } cout << endl; } //for creating three dimensional array of 2 by 3 by 4 double float double ***ptr3; ptr3 = new double**[2]; for( int i = 0 ; i < 2 ; i++) { ptr3[i] = new double*[3]; } for( int i = 0 ; i < 2 ; i++) { for( int j = 0 ; j < 3 ; j++) { ptr3[i][j] = new double[4]; } } for( int i = 0 ; i < 2 ; i++) { for( int j = 0 ; j < 3 ; j++) { for( int k = 0 ; k < 4 ; k++) { ptr3[i][j][k] = ( i * 3 + j ) * 4.1 + k * 0.1; } } } cout << "\nThree dimensions array of 2 by 3 by 4 double float :\n"; for( int i = 0 ; i < 2 ; i++) { for( int j = 0 ; j < 3 ; j++) { for( int k = 0 ; k < 4 ; k++) { cout <<"\nptr3(" << i << "," << j << "," << k << ") = " << setprecision(4) << { ptr3[i][j][k]; } } } } return 0; }