//二级指针内存模型混合实战 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h>//将内存模型①和内存模型②的数据拷贝到内存模型③ char ** threemodel(char **pin1,int num1,char (*pin2)[20],int num2,char **pin3,int *pnum3){if (pin1==NULL){printf("pin1==NULL\n");}if (pin2 == NULL){printf("pin2==NULL\n");}if (num1 == 0){printf("num1 == 0\n");}if (num2 == 0){printf("num2 == 0\n");}int num3 = num1 + num2;int i = 0, j = 0,index=0;//分配二级指针内存堆空间pin3 = (char **)malloc(sizeof(char *)*num3);if (pin3==NULL){printf("分配二级内存失败!");return NULL;}for (i = 0; i < num1; i++){//获取本段字符串的长度int temp1 = (int)strlen(pin1[i]) + 1;//strlen()函数获取的是字符串(不包括'\0')的长度,因此长度需要+1//分配一级指针内存堆空间pin3[index] = (char *)malloc(sizeof(char)* temp1);if (pin3[index] == NULL){printf("分配一级内存失败!");return NULL;}//开始拷贝数据 strcpy(pin3[index], pin1[i]);index++;}for (j = 0; j < num2; j++){int temp1 = (int)strlen(*(pin2 + j)) + 1;//*(pin2 + j)==pin2[j],但是*(pin2 + j)便于理解//分配一级指针内存堆空间pin3[index] = (char *)malloc(sizeof(char)* temp1);if (pin3[index] == NULL){printf("分配一级内存失败!");return NULL;}//开始拷贝数据strcpy(pin3[index], *(pin2 + j));index++;}*pnum3 = num3;return pin3; }void main() {//第一种内存模型char *pstr[3] = {"111","222","333"};//第二种内存模型char tarr[3][20] = {"aaa","bbb","ccc"};//第三种内存模型char **pdata = NULL;int num = 0,i=0;pdata = threemodel(pstr, 3, tarr, 3, pdata, &num);if (pdata!=NULL){for (i = 0; i < num; i++){if (pdata[i]!=NULL){printf("%s\n", pdata[i]);//释放当前内存free(pdata[i]);//消除野指针pdata[i] = NULL;}}//释放pdata所指向的内存空间free(pdata);pdata = NULL;}system("pause"); }