#include <iostream> #include <string.h> using namespace std; int get_Array(char **srcp1 , int num1, char (*srcp2)[20] , int num2 , char ***ans,int *mynum) { int ret=0 ; int num=0; char **tmp = NULL; if(srcp1 == NULL || srcp2 == NULL || mynum == NULL) { ret = -1; printf("srcp1 == NULL || srcp2 == NULL || mynum == NULL \n"); return ret; } //准备在堆上分配内存 //num = num1 + num2; printf("%d\n",num); //分配指针数组的内存 tmp = (char **)malloc(sizeof(char *)*num); if(tmp == NULL) { ret -2; printf("tmp == NULL:(char **)malloc(sizeof(char *)*num) \n"); return -1; } //分配第二堆内存-->第一钟 for(int i=0;i<num1;i++) { tmp[i] = (char *)malloc(strlen(srcp1[i])+1); if(tmp[i]==NULL) { ret = -3; printf("tmp[%d]==NULL:(char *)malloc(strlen(srcp1[i])+1)\n",i); return ret; } strcpy(tmp[i],srcp1[i]); } //分配第二堆内存-->第二钟 for(int i=0;i<num2;i++) { tmp[i] = (char *)malloc(strlen(srcp2[i])+1); if(tmp[i]==NULL) { ret = -4; printf("tmp[%d]==NULL:(char *)malloc(strlen(srcp2[i])+1)\n",i); return ret; } strcpy(tmp[i],srcp2[i]); } *ans = tmp; *mynum = num; return 0; } int get_Array_Free(char ***p , int numlen) { int i; char **tmp = NULL; if(p==NULL) { printf("p==NULL\n"); return -1; } tmp = *p; for(i =0 ;i<numlen;i++) { if(tmp[i] != NULL) { free(tmp[i]); } } free(tmp); *p = NULL; //避免野指针 } int main() { int ret = 0; int mynum = 0; char *p1[] = {"1111","222","4444","5555555"}; char p2[4][20] = {"bbbb" , "aaaaa" ,"22222" ,"cccccc"}; char **p3=NULL; ret = get_Array(p1,4,p2,4,&p3,&mynum); if(ret != 0) { printf("get_Array error:ret \n",ret); } for(int i=0;i<mynum;i++) printf("%s\n",p3[i]); get_Array_Free(&p3 , mynum); return 0; }