In C ++, dynamic one-dimensional arrays are implemented through the dynamic allocation of space by malloc. Dynamic Two-dimensional arrays can also be implemented through the dynamic allocation of space by malloc.
In fact, the C ++ language does not have a two-dimensional array, at least it does not directly support two-dimensional arrays. Instead, it is replaced by an array ", A two-dimensional array can be viewed as an array composed of pointers to arrays. For a two-dimensional array p [I] [j], the compiler uses the formula * (p + I) + j) to obtain the value of the array element:
1. p + I calculates the row pointer.
2. * (P + I) is a pointer pointing to the first element address of the row.
3. * (P + I) + j to get the address of the specific element.
4. * (p + I) + j) to obtain the element value.
Based on the above principle, we can allocate a pointer array, and then allocate space for each element of the pointer array to dynamically allocate a two-dimensional array. The following is an implementation of dynamically allocating two-dimensional arrays written by myself. It is applicable to any type of two-dimensional arrays and can be directly used. Type Definition and error code:
- Typedef unsigned char MK_Byte;
- # Define SUCCESS 0/* No error */
- # Define MFAILED 1/* General failure */
- # Define MNOMEMORY 2/* Out of memory */
- Statement
- // Ensure Initialization
- # Define DeclareTwoDArray (ATYPE, iname) ATYPE **Iname=NULL
- // Define your own malloc and free to ensure proper memory operations
- # Define MKMALLOC (nsize) malloc (nsize)
- # Define MKFREE (name )\
- If (NULL! = Name )\
- Free (name );\
- Name=NULL
- How to Write C ++ project development and project plan correctly
- Summary Notes on learning and exploring C ++ library functions
- In-depth demonstration of high security of C ++
- Describes in detail how to accurately Write C ++ languages.
- In-depth demonstration of high security of C ++