//二級指針內存模型混合實戰 #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"); }
?
?
?