Commit 270cfc
2024-03-31 14:13:00 Qwas: 新增/dev/null .. "b/C\350\257\255\350\250\200/C\350\257\255\350\250\200malloc\345\222\214free\345\207\275\346\225\260.md" | |
@@ 0,0 1,53 @@ | |
+ | # C语言malloc和free函数 |
+ | |
+ | ## malloc 使用 |
+ | |
+ | ```c |
+ | #include <stdio.h> |
+ | #include <stdlib.h> |
+ | |
+ | int main() |
+ | { |
+ | int *p = NULL; |
+ | p = malloc(sizeof(int)); // 申请空间 返回类型 void * |
+ | |
+ | if(p == NULL) |
+ | { |
+ | printf("malloc error! \n"); |
+ | exit(1); |
+ | } |
+ | *p = 10; // 在空间存值 |
+ | printf("%d\n",*p); |
+ | |
+ | free(p); // 释放内存 |
+ | |
+ | exit(0); |
+ | } |
+ | ``` |
+ | |
+ |  |
+ | |
+ | ```c |
+ | #include <stdio.h> |
+ | #include <stdlib.h> |
+ | |
+ | int main() { |
+ | int *p; |
+ | int num = 5; |
+ | int i; |
+ | |
+ | p = malloc(sizeof(int) * num); |
+ | |
+ | for (i = 0; i < num; i++) |
+ | scanf("%d", &p[i]); |
+ | |
+ | for (i = 0; i < num; i++) |
+ | printf("%d ", p[i]); |
+ | |
+ | printf("\n"); |
+ | |
+ | exit(0); |
+ | } |
+ | ``` |
+ | |
+ |  |