企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # 分别在堆上和栈上分配空间 ![](https://box.kancloud.cn/5e56c69aba49f60a2060623f9a11429b_1399x643.png) ~~~ #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<string.h> #include<stdlib.h> void printArray(int **arr,int len) { for (int i = 0; i < len; ++i) { printf("%d ",*arr[i]); } } void test01() { //堆上分配指针数组 int **pArray = malloc(sizeof(int *)* 6); //栈上分配数据空间 int a1 = 100; int a2 = 200; int a3 = 300; int a4 = 400; int a5 = 500; int a6 = 600; #if 0 pArray[0] = &a1; pArray[1] = &a2; pArray[2] = &a3; pArray[3] = &a4; pArray[4] = &a5; pArray[5] = &a6; #endif *(pArray + 0) = &a1; *(pArray + 1) = &a2; *(pArray + 2) = &a3; *(pArray + 3) = &a4; *(pArray + 4) = &a5; *(pArray + 5) = &a6; printArray(pArray, 6); //释放数组内存 if (pArray != NULL) { free(pArray); pArray = NULL; } } void test02() { int* pArray[5]; for (int i = 0; i < 5; ++i) { //一个个申请 pArray[i] = malloc(4); *(pArray[i]) = 100 + i; } printArray(pArray, 5); //释放堆内存 for (int i = 0; i < 5; ++i) { if (pArray[i] != NULL) { //要一个个释放 free(pArray[i]); pArray[i] = NULL; } } } int main(){ //test01(); test02(); system("pause"); return EXIT_SUCCESS; } ~~~ # 二级指针做函数参考 ~~~ #include <iostream> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> void allocateSpace(int **temp) { int *arr = (int *)malloc(sizeof(int) * 10); for (int i = 0; i < 10; ++i) { arr[i] = i + 1; } //指针间接赋值 *temp = arr; } void printArray(int *arr, int len) { for (int i = 0; i < len; ++i) { printf("%d ", arr[i]); } } void freeSpace(int **arr) { if (arr == NULL) { return ; } if (*arr != NULL) { free(*arr); *arr = NULL; arr = NULL; } } void test01() { int *pArray = NULL; allocateSpace(&pArray); printArray(pArray, 10); freeSpace(&pArray); if (pArray == NULL) { printf("\npArray被置空"); } } int main() { test01(); getchar(); return 0; } ~~~