Comparison of dynamic memory space initialization Methods
1. initialize the SDK using the following method;
2. initialize by moving the pointer;
******************/ # Include <stdio. h> # include <stdlib. h> int main (void) {int * P = (int *) malloc (5 * sizeof (INT); printf ("this is the subscript method initialization method: \ n "); for (INT I = 0; I <5; I ++) {P [I] = I + 1; printf ("% d \ t ", P [I]);} Free (p); Return 0 ;}
****************** /# Include <stdio. h> # include <stdlib. h> int main (void) {int I; int * P = (int *) malloc (5 * sizeof (INT); printf ("this is initiated by moving the pointer: \ n "); int * Pv = P; for (I = 0; I <5; I ++) {* Pv = I + 1; printf ("% d \ t", * PV); PV ++;} Free (p); Return 0 ;}
both methods can initialize the dynamically applied memory space, however, it is obvious that the first method (subscript method) is more convenient and safer than the second method (move pointer method. Cause: In the second method (move pointer mode), if you move the defined pointer variable directly, when the memory space is finally released, you may forget to move the pointer position to the initial position (this method is not recommended, of course), and directly pass the pointer to free (void * pointer) to release the space. However, at this time, the pointer position has changed and is no longer the first address of the memory space. Therefore, runtime errors will occur when the memory is released. To solve this problem, we need to define a temporary pointer variable to point to the position pointed to by the original pointer, and then use this temporary pointer variable to initialize the memory space, finally, pass the original pointer to free (void
* pointer) to release the memory space.
I think it is better to use the subscript method to initialize the dynamically applied memory space!