// Ex642.cc // Sec. 6.4 of lecture // Dynamic arrays 2D #include main() { int n,m,i,j; double *a, **b; cout << " Eingabe Zeilen n : "; cin >> n; cout << " Eingabe Spalten m : "; cin >> m; //-------------------------------------------------------------------- // Version a a = new double[n*m]; // Allocate array // initialize a for (i = 0; i < n; i++ ) { for (j = 0; j < m; j++) { a[i*m+j] = (i+1)*(j+1); } } // output a; cout << endl << " Matrix A " << endl; for (i = 0; i < n; i++ ) { for (j = 0; j < m; j++) { cout << " " << a[i*m+j]; } cout << endl; } cout << endl; delete [] a; // Deallocate array //-------------------------------------------------------------------- // Version b (even more dynamic) // Pointers at pointers b = new (double* [n]); // Allocate row pointers for (i = 0; i < n; i++) { b[i] = new double[m]; // Allocate rows } // There is no guarantee that the rows are stored // linearly in memory // initialize b for (i = 0; i < n; i++ ) { for (j = 0; j < m; j++) { b[i][j] = (i+1)*(j+1); } } // output b; cout << endl << " Matrix B " << endl; for (i = 0; i < n; i++ ) { for (j = 0; j < m; j++) { cout << " " << b[i][j]; } cout << endl; } cout << endl; for (i = n-1; i >= 0; i--) { delete [] b[i]; // Deallocate rows } delete [] b; // Deallocate row pointers }