分别在堆上和栈上分配空间

image.png

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<stdio.h>
  3. #include<string.h>
  4. #include<stdlib.h>
  5. void printArray(int **arr,int len)
  6. {
  7. for (int i = 0; i < len; ++i)
  8. {
  9. printf("%d ",*arr[i]);
  10. }
  11. }
  12. void test01()
  13. {
  14. //堆上分配指针数组
  15. int **pArray = malloc(sizeof(int *)* 6);
  16. //栈上分配数据空间
  17. int a1 = 100;
  18. int a2 = 200;
  19. int a3 = 300;
  20. int a4 = 400;
  21. int a5 = 500;
  22. int a6 = 600;
  23. #if 0
  24. pArray[0] = &a1;
  25. pArray[1] = &a2;
  26. pArray[2] = &a3;
  27. pArray[3] = &a4;
  28. pArray[4] = &a5;
  29. pArray[5] = &a6;
  30. #endif
  31. *(pArray + 0) = &a1;
  32. *(pArray + 1) = &a2;
  33. *(pArray + 2) = &a3;
  34. *(pArray + 3) = &a4;
  35. *(pArray + 4) = &a5;
  36. *(pArray + 5) = &a6;
  37. printArray(pArray, 6);
  38. //释放数组内存
  39. if (pArray != NULL)
  40. {
  41. free(pArray);
  42. pArray = NULL;
  43. }
  44. }
  45. void test02()
  46. {
  47. int* pArray[5];
  48. for (int i = 0; i < 5; ++i)
  49. {
  50. //一个个申请
  51. pArray[i] = malloc(4);
  52. *(pArray[i]) = 100 + i;
  53. }
  54. printArray(pArray, 5);
  55. //释放堆内存
  56. for (int i = 0; i < 5; ++i)
  57. {
  58. if (pArray[i] != NULL)
  59. {
  60. //要一个个释放
  61. free(pArray[i]);
  62. pArray[i] = NULL;
  63. }
  64. }
  65. }
  66. int main(){
  67. //test01();
  68. test02();
  69. system("pause");
  70. return EXIT_SUCCESS;
  71. }

二级指针做函数参考

  1. #include <iostream>
  2. #include <stddef.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. void allocateSpace(int **temp) {
  7. int *arr = (int *)malloc(sizeof(int) * 10);
  8. for (int i = 0; i < 10; ++i) {
  9. arr[i] = i + 1;
  10. }
  11. //指针间接赋值
  12. *temp = arr;
  13. }
  14. void printArray(int *arr, int len) {
  15. for (int i = 0; i < len; ++i) {
  16. printf("%d ", arr[i]);
  17. }
  18. }
  19. void freeSpace(int **arr) {
  20. if (arr == NULL) {
  21. return ;
  22. }
  23. if (*arr != NULL) {
  24. free(*arr);
  25. *arr = NULL;
  26. arr = NULL;
  27. }
  28. }
  29. void test01() {
  30. int *pArray = NULL;
  31. allocateSpace(&pArray);
  32. printArray(pArray, 10);
  33. freeSpace(&pArray);
  34. if (pArray == NULL) {
  35. printf("\npArray被置空");
  36. }
  37. }
  38. int main() {
  39. test01();
  40. getchar();
  41. return 0;
  42. }