#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>//二级指针做函数参数的输入特性//主调函数分配内存,被调用函数使用voidprintArray(int** pArray,int len){for(int i =0; i < len; i++){printf("%d\n",*pArray[i]);}}voidtest01(){//在堆区分配内存int**p =malloc(sizeof(int*)*5);//在栈上创建数据int a1 =10;int a2 =20;int a3 =30;int a4 =40;int a5 =50;
p[0]=&a1;
p[1]=&a2;
p[2]=&a3;
p[3]=&a4;
p[4]=&a5;printArray(p,5);if(p !=NULL){free(p);
p =NULL;}}voidtest02(){//在栈上创建int*pArray[5];for(int i =0; i <5; i++){
pArray[i]=malloc(4);*(pArray[i])=100+ i;}int len =sizeof(pArray)/sizeof(int*);printArray(pArray,len);for(int i =0; i <5; i++){if(pArray !=NULL){free(pArray[i]!=NULL);
pArray[i]=NULL;}}}intmain(){//test01();test02();return EXIT_SUCCESS;}
输出特性
代码示例:
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>voidallocateSpace(int**p){int*arr =malloc(sizeof(int)*10);for(int i =0; i <10; i++){
arr[i]= i +10;}*p = arr;}voidprintArray(int**pArray,int len){for(int i =0; i <10; i++){printf("%d\n",(*pArray)[i]);}}voidfreeSpace(int**p){if(*p !=NULL){free(*p);*p =NULL;}}voidtest01(){int*p =NULL;allocateSpace(&p);printArray(&p,10);freeSpace(p);
p =NULL;if(p ==NULL){printf("空指针\n");}else{printf("野指针\n");}}intmain(){test01();return EXIT_SUCCESS;}