1,连接
将两个二级指针数组做输入,用三级指针做输出,在被调函数里分配内存。
/*该函数的声明里,char (*b)[30],不能修改为char** b,或者char (*b)[],因为二级指针b指向一个二维数组,而不是指针数组,char (*b)[30]与char** b两个b唯一的区别在于两者的步长不一致。此处需要注意。*/
int link(char** a, int num_a, char (*b)[30], int num_b, char*** out, int* num_out)
{
char** tmp_ptr = NULL;
int tmp_num = 0, tmp_len = 0;
int i;
if(num_out == NULL)
return -1;
tmp_num = num_a + num_b;
tmp_ptr = (char**)malloc(sizeof(char*) * tmp_num);
if(tmp_ptr == NULL)
return -1;
memset(tmp_ptr, 0, tmp_num);
tmp_num = 0;
for(i = 0; i < num_a; i++)
{
tmp_len = strlen(a[i]) + 1;
tmp_ptr[tmp_num] = (char*)malloc(sizeof(char) * tmp_len);
if(tmp_ptr[tmp_num] == NULL)
goto ERROR_FREE;
strcpy(tmp_ptr[tmp_num], a[i]);
tmp_num++;
}
for(i = 0; i < num_b; i++)
{
tmp_len = strlen(b[i]) + 1;
tmp_ptr[tmp_num] = (char*)malloc(sizeof(char) * tmp_len);
if(tmp_ptr[tmp_num] == NULL)
goto ERROR_FREE;
strcpy(tmp_ptr[tmp_num], b[i]);
tmp_num++;
}
*out = tmp_ptr;
*num_out = tmp_num;
return 0;
ERROR_FREE:
for(i = 0; i < num_a + num_b; i++)
{
if(tmp_ptr[i] != 0)
free(tmp_ptr[i]);
}
free(tmp_ptr);
return -2;
}
2、打印
void print(char** ptr, int num)
{
int i = 0;
if(ptr == NULL)
return;
while(i < num)
{
printf("%s\n", ptr[i]);
i++;
}
}
3、销毁
void destory(char*** ptr, int num)
{
int i;
char** tmp;
if(ptr == NULL)
return;
tmp = *ptr;
for(i = 0; i < num; i++)
{
free(tmp[i]);
tmp[i] = NULL;
}
free(tmp);
*ptr = NULL;
}
4、测试main
int main()
{
char* a[] = {"1111", "2222", "3333"};
char b[3][30] = {"4444", "5555", "6666"};
int num_a = 3;
int num_b = 3;
char** out = NULL;
int num_out = 0;
link(a, num_a, b, num_b, &out, &num_out);
print(out, num_out);
destory(&out, num_out);
return 0;
}