Blame
270cfc | Qwas | 2024-03-31 14:13:00 | 1 | # C语言malloc和free函数 |
2 | ||||
3 | ## malloc 使用 |
|||
4 | ||||
5 | ```c |
|||
6 | #include <stdio.h> |
|||
7 | #include <stdlib.h> |
|||
8 | ||||
9 | int main() |
|||
10 | { |
|||
11 | int *p = NULL; |
|||
12 | p = malloc(sizeof(int)); // 申请空间 返回类型 void * |
|||
13 | ||||
14 | if(p == NULL) |
|||
15 | { |
|||
16 | printf("malloc error! \n"); |
|||
17 | exit(1); |
|||
18 | } |
|||
19 | *p = 10; // 在空间存值 |
|||
20 | printf("%d\n",*p); |
|||
21 | ||||
22 | free(p); // 释放内存 |
|||
23 | ||||
24 | exit(0); |
|||
25 | } |
|||
26 | ``` |
|||
27 | ||||
28 |  |
|||
29 | ||||
30 | ```c |
|||
31 | #include <stdio.h> |
|||
32 | #include <stdlib.h> |
|||
33 | ||||
34 | int main() { |
|||
35 | int *p; |
|||
36 | int num = 5; |
|||
37 | int i; |
|||
38 | ||||
39 | p = malloc(sizeof(int) * num); |
|||
40 | ||||
41 | for (i = 0; i < num; i++) |
|||
42 | scanf("%d", &p[i]); |
|||
43 | ||||
44 | for (i = 0; i < num; i++) |
|||
45 | printf("%d ", p[i]); |
|||
46 | ||||
47 | printf("\n"); |
|||
48 | ||||
49 | exit(0); |
|||
50 | } |
|||
51 | ``` |
|||
52 | ||||
53 |  |