17.1 动态存储分配

  1. 需要的头文件
  2. 对应的函数
    1. malloc:分配内存块,但不初始化
    2. calloc:分配内存块,并且对内存块进行清除
    3. realloc:调整先前分配的内存块
  3. 返回值 void * :即一个内存地址
  4. 空指针:NULL

    17.2 动态分配字符串

  5. 使用 malloc 函数为字符串分配内存时,复制操作会把 malloc 的通用指针转换成为对应类型的,当然最好自己强制转换(1)

  6. 使用 malloc 分配一个字符串(2)
  1. // 1
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. int main()
  5. {
  6. int *p;
  7. p = (int *)malloc(1000);
  8. }
  9. // 2
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. char *concat(char *s1,char *s2);
  14. int main()
  15. {
  16. char *p = concat("abc","def");
  17. printf("%s",p);
  18. return 0;
  19. }
  20. char *concat(char *s1,char *s2)
  21. {
  22. char *result=NULL;
  23. result = (char *)malloc(strlen(s1)+strlen(s2)+1);
  24. // 如果 result 为空就退出
  25. strcpy(result,s1);
  26. strcat(result,s2);
  27. return result;
  28. }
  29. // 输出
  30. abcdef

17.3 动态分配数组

  1. 使用 malloc 进行动态分配(1)
  1. // 1
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. int main()
  5. {
  6. int n;
  7. int *a;
  8. printf("输入你想要的数组大小:");
  9. scanf("%d",&n);
  10. a = (int *)malloc(n*sizeof(int));
  11. printf("%d",sizeof(a)); // 8
  12. return 0;
  13. }

17.4 释放存储

  1. free 函数:free(void *ptr)
  1. p = malloc(...);
  2. q = malloc(...);
  3. p = q;
  4. free(p);

17.5 realloc() 函数

  1. 【作用】:实现对内存大小的重新分配
  2. 【函数原型】:_void* realloc (void* ptr, size_t size);_
    1. 【参数解释】ptr 指向要重新分配的空间,size 重新分配的大小
  3. 【注意】
    1. ptr 为 null ,即表示新开辟一个空间,和 malloc 相同
    2. size 为 null ,即新空间大小为空,和 free 相同
    3. ptr 在重新分配完成后会被回收
    4. 新的内存空间地址,可能和原来一样,也可能不一样
  1. #include <stdio.h>
  2. #include <stlib.h>
  3. int main()
  4. {
  5. // 先动态分配一个内存地址及其对应的内存空间
  6. int *test = (int *)malloc(sizeof(int)*10);
  7. printf("%d\n",test);
  8. // 用新指针指以下
  9. int *re = test;
  10. // 重新分配内存空间
  11. test = (int *)realloc(re,sizeof(int)*100);
  12. printf("%d",test);
  13. return 0;
  14. }

17.6 指向指针的指针

  1. #include <stdio.h>
  2. int main()
  3. {
  4. int a = 12;
  5. int *p = &a;
  6. int **q = &p;
  7. printf("%d",**q); // 12
  8. return 0;
  9. }

image.png

17.7 指向函数的指针

参考

  1. malloc、calloc、realloc之间的区别