The malloc function c

Variables used in the program to be stored prior to use processed data and various status information, variables must

Define arrangements for storage space. Global variables and store those static variables determined at compile time

For local variables allocated in the definition of the storage unit, the size of this variable is statically determined

Static storage arrangements advantages, easy to achieve high efficiency. However, when the number can not be determined, it is difficult to engage

c provides dynamic storage management focus malloc function to dynamically allocate memory, but in the end they have to release free function

Here is an example, suppose you n summing the number range of n can not be estimated, have dynamic implementation summation

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 int main()
 4 {
 5     int n,sum ,*p;
 6     scanf("%d",&n);
 7     if((p = (int *)malloc(n*sizeof(int))) == NULL)
 8     {
 9         printf("Sorry!\n");
10         exit(1);
11     }
12     
13     for(int i = 0;i < n;i++)
14     scanf("%d",p+i);
15     sum = 0;
16     
17     for(int i = 0;i < n;i++)
18     sum += *(p+i);
19     printf("sum = %d\n",sum);
20     free(p);
21     
22     return 0;
23 }

 

Guess you like

Origin www.cnblogs.com/mch5201314/p/11567888.html