C ++ dynamically allocates 2D and 3D arrays and arrays.
Project 1:
Objective: To be familiar with c ++ dynamic memory allocation
Description: uses a c ++ program to define a dynamic array class. uses the new and delete operators to define a dynamic two-dimensional array and a three-dimensional array.
// Main. cpp // main program class # include <iostream> # include "DynamicArray. h "# include" DynamicArray3d. h "using namespace std; int main () {cout <" Hello world! "<Endl; DynamicArray a;. printArray (); DynamicArray3d B; B. printArray (); return 0;} // DynamicArray. h // two-dimensional array header file # ifndef DYNAMICARRAY_H # define DYNAMICARRAY_H # include <iostream> using namespace std; class DynamicArray {public: DynamicArray (int m = 5, int n = 5 );~ DynamicArray (); void printArray (); private: int ** m_pArray; // used to store the internal array int m_iSize; int n_iSize; // used to record the amount of memory occupied }; # endif // DYNAMICARRAY_H // DynamicArray. cpp // two-character array source file # include "DynamicArray. h "DynamicArray: DynamicArray (int m, int n) {int I, j; m_iSize = m; n_iSize = n; m_pArray = new int * [m_iSize]; for (I = 0; I <m_iSize; I ++) m_pArray [I] = new int [n_iSize]; for (I = 0; I <m_iSize; I ++) for (j = 0; j <n _ ISize; j ++) {m_pArray [I] [j] = I + 10 * j ;}// destructor DynamicArray ::~ DynamicArray () {for (int I = m_iSize; I> 0;) delete [] m_pArray [-- I]; delete [] m_pArray;} void DynamicArray: printArray () {int I, j; cout <"Print Array:" <endl; for (I = 0; I <m_iSize; I ++) {for (j = 0; j <n_iSize; j ++) cout <m_pArray [I] [j] <""; cout <endl ;}// DynamicArray3d. h // 3D array header file # ifndef DYNAMICARRAY3D_H # define DYNAMICARRAY3D_H # include <iostream> using namespace std; class DynamicArray3d {Public: DynamicArray3d (int m = 5, int n = 5, int o = 5 );~ DynamicArray3d (); void printArray (); private: int *** m_pArray; // used to store the internal array int m_iSize; int n_iSize; // used to record the memory usage int o_iSize ;};# endif // DYNAMICARRAY3D_H // 3D Array source file # include "/home/empty/c/Array/include/DynamicArray3d. h "DynamicArray3d: DynamicArray3d (int m, int n, int o) {int I, j, k; m_iSize = m; n_iSize = n; o_iSize = o; m_pArray = new int ** [m_iSize]; for (I = 0; I <m_iSize; I ++) m_pArray [I] = new int *[ N_iSize]; for (I = 0; I <m_iSize; I ++) for (j = 0; j <n_iSize; j ++) m_pArray [I] [j] = new int [o_iSize]; // enter the three-dimensional array value: for (I = 0; I <m_iSize; I ++) for (j = 0; j <n_iSize; j ++) for (k = 0; k <o_iSize; k ++) m_pArray [I] [j] [k] = I * 100 + j * 10 + k;} DynamicArray3d ::~ DynamicArray3d () {// dtor} void DynamicArray3d: printArray () {int I, j, k; for (I = 0; I <m_iSize; I ++) {for (j = 0; j <n_iSize; j ++) {for (k = 0; k <o_iSize; k ++) cout <m_pArray [I] [j] [k] <""; cout <";}cout <endl ;}}