Pointer & dynamic memory allocation, C language pointer
Dynamic Memory Allocation Mechanism in C ++
C ++ uses new and delete to allocate and release dynamic memory on the stack.
Note. All pointers should be initialized.
If the dynamic memory to which the Pointer Points is released or does not point to a valid address, set the pointer to nullptr. Otherwise, the memory will leak.
Variable:
Double * pvalue {};
Pvalue = new double;
* Pvalue = 9.0;
Or
Double * pvalue {};
Pvalue = new double {9.0 };
Or merge into one sentence.
Double * pvalue {new double {9.0 }};
Delete pvalue;
Array:
Char * pstr {new char [20]};
Delete [] pstr;
Pstr = nullptr;
Can be initialized by the way: int * data {new int [10] {2, 3, 4 }};
Multi-dimensional array:
Double (* pbeans) [4] {};
Pbeans = new double [3] [4];
Or merge as one step: double (* pbeans) [4] {new double [3] [4]};
Delete [] pbeans;
Pbeans = nullptr;
Dynamic Memory Allocation Mechanism in C Language
Malloc:
Double * ptd;
Ptd = (double *) malloc (N * sizeof (double ));
Free (ptd );
Request N double-Type Spaces
Calloc:
Long * newmem;
Newmem = (long *) calloc (N, sizeof (long ));
The first parameter is the number of memory units required, and the second parameter is the size of each unit in bytes. Calloc sets all parts of the block to 0.
Dynamic Memory Allocation in a variable-length array (VLA:
Int n = 5;
Int m = 6;
Int ar [n] [m]; // Variable Length Array
Int (* p1) [6];
Int (* p2) [m]; // Variable Length Array
P1 = (int (*) [6]) malloc (n * 6 * sizeof (int ));
P2 = (int (*) [m]) malloc (n * m * sizeof (int); // Variable Length Array
Note: columns must be specified during array transmission as parameters.
For example, double (int ar [] [6]);