C ++ has two main ways to create a dynamic two-dimensional array: 1. use an array pointer to allocate a pointer array, store its first address in B, and then assign an array int ** B = new int * [row] to each element of the pointer array; // allocate a pointer array and save its first address in B for (I = 0; I <row; I ++) // assign an array B [I] = new int [col] to each element of the pointer array; to release a dynamic two-dimensional array defined in this method, you must first release the array pointed to by each element of the pointer array, and then release the pointer array: for (I = 0; I <row; I ++) {delete [col] B [I]; B [I] = NULL;} delete [row] B; B = NULL;
Int _ tmain (int argc, _ TCHAR * argv []) {int row, column; cin> row> column; // method 1 // apply for a space int ** a = new int * [row]; for (int I = 0; I <row; I ++) a [I] = new int [column]; // use space for (int j = 0; j <row; j ++) for (int k = 0; k <column; k ++) a [j] [k] = rand () % 100; for (int j = 0; j <row; j ++) {cout <endl; for (int k = 0; k <column; k ++) {a [j] [k] = rand () % 100; cout <a [j] [k] <";}}// release space for (int I = 0; I <row; I ++) {delete a [I]; a [I] = NULL;} delete [row] a; a = NULL; return 0 ;}
Running result: 2. Use vector
Int _ tmain (int argc, _ TCHAR * argv []) {int row, column; cin> row> column; // method 2 // apply for Space vector <int> a (row, vector <int> (column); // use space for (int j = 0; j <row; j ++) for (int k = 0; k <column; k ++) a [j] [k] = rand () % 100; for (int j = 0; j <row; j ++) {cout <endl; for (int k = 0; k <column; k ++) {a [j] [k] = rand () % 100; cout <a [j] [k] <";}} return 0 ;}
The running result is: