二级指针的三种内存模型 分类: C语言学习 2015-03-30 21:04 153人阅读 评论(0) 收藏
/* Level tow point have three cache model */ #include <stdio.h> #include <stdlib.h> int Print(char**pArr); int Print02(char**pArr,int num); int GetMem(char***thirdModel,int len); int Destory(char***thirdModel,int len); int main() { int i=0; char **thirdModel=NULL; //first cache model char *firstModel[10]={"abc","linux","unix",0}; //second cache model char secondModel[3][10]={"abc","linux","unix"}; //third cache model GetMem(&thirdModel,4); strcpy(*(thirdModel+0),"abc"); strcpy(*(thirdModel+1),"linux"); strcpy(*(thirdModel+2),"unix"); printf("firstModel start\n"); Print(firstModel); printf("secondModel start \n"); Print02(secondModel,4); printf("thirdModel start\n"); Print(thirdModel); Destory(&thirdModel,4); return 0; } int Print(char**pArr) { int ret=0,i=0; if(NULL==pArr) { ret=-1; printf("arg is null error:%d\n",ret); return ret; } while(*pArr) { printf("%s\n",*pArr); ++pArr; } return ret; } int Print02(char**pArr,int num) { int ret=0,i=0; //二级指针和指向数组的指针不一样。 char(*arr)[10]=pArr; if(NULL==pArr) { ret=-1; printf("arg is null error:%d\n",ret); return ret; } for(i=0;i<num;i++) { printf("%s\n",*(arr+i)); } return ret; } //三级指针做输出模型 int GetMem(char***thirdModel/*out*/,int len) { int ret=0,i=0; if(NULL==thirdModel || len<=0) { ret=-1; return ret; } char**tmp=(char**)malloc(len*sizeof(char*)); if(NULL==tmp) { ret=-1; return ret; } for(i=0;i<len-1;i++) { *(tmp+i)=(char*)malloc(100*sizeof(char)); if(NULL==*(tmp+i)) { ret=-1; return ret; } } *(tmp+(len-1))=0; *thirdModel=tmp; return ret; } //销毁堆上的内存 int Destory(char***thirdModel,int len) { int ret=0,i=0; char **tmp=NULL; if(NULL==thirdModel || len<=0) { ret=-1; return ret; } tmp=*thirdModel; for(i=0;i<len;i++) { if(NULL!=*(tmp+i)) { free(*(tmp+i)); *(tmp+i)=NULL; } } free(tmp); *thirdModel=NULL; return ret; }
版权声明:本文为博主原创文章,未经博主允许不得转载。