Regain dynamic memory allocation in C Language
Disadvantages of traditional array allocation in dynamic memory: 1 the length of the array must be specified in advance, it can only be a long integer. It cannot be an array defined in the traditional form of variable 2. The memory program of this array cannot manually release 3. Once the array is defined, the system will allocate the storage space for the array until the function is running. The length of the array cannot be dynamically expanded or reduced by 5 During the function operation. why do I need to dynamically allocate memory? dynamic memory allocation example -- Constructing a dynamic array static memory allocation and dynamic memory allocation cross-function memory usage # include
Void f (void) {int a [5] = {0, 1, 2, 3, 4} // you cannot manually release it. You need to release the system after running this function.} int main () {f () ;}# incliude
# Include
Int main () {int I = 5;/* Static allocation * // * Eight bytes allocated p storage first address number */int * P = (int *) malloic (4);/* The second int * is forcibly converted to the int type * // * indicates four bytes, but only the first address indicates */free (p ); // free (p) indicates to release the memory pointed to by p. // the memory of p itself cannot be manually released by programmers.}/* malloc can only return the first address. */p occupies static memory. the allocated p refers to the memory dynamics.
// Malloc function learning dynamic memory allocation # include
Void f (int * q) {* q = 200; if free (p) is written here, it is meaningless in the main function.} int main () {int * p = (int *) malloc (sizeof (int) * p = 10; printf ("% d \ n", * p); f (p ); /* free (p); */This is also incorrect because the memory printf ("% d \ n", * p) has been released;} zhan storage structure heap allocation war zone redemption