Dynamic memory allocation: a memory allocation method that can be opened and released at any time as needed.
The timing of allocation and release is completely determined by the programmer. Since there is no data declaration, this part of the space has no name.
The data in it cannot be referenced by the variable name or the array name as you can with the variable or array, it can only be accessed through the pointer variable.
Note that malloc and free generally appear in pairs, as long as the successfully applied space must be released after use, otherwise it will cause memory leaks.
1 #include<stdio.h> 2 #include<stdlib.h> 3 int sum( int *, int ); /// function declaration 4 int mian() 5 { 6 int n,s,i,* p; 7 scanf( " %d " ,& n); 8 p=( int *) malloc (n* sizeof ( int )); /// The return value of malloc is void*, which is inconsistent with the p type and needs to be converted, if not then automatically but with a warning 9 if (p==NULL) /// dynamic memory allocation failed 10 exit( 1 ); /// Stop running the program 11 for (i= 0 ;i<=n- 1 ;i++ ) 12 scanf( " %d " ,p+ 1 ); /// Input of pointer variable 13 s= sum(p,n); /// Call the function to pass the pointer variable 14 printf( " %d\n " ,s); 15 free (p); /// Release the space allocated by the malloc() function in the memory 16 return 0 ; 17 } 18 int sum( int *p, int n) 19 { 20 int i,s=0; 21 for(i=0;i<=n-1;i++) 22 s=s+(*p++); 23 return s; 24 }