/*
功能:1.把指针数组p1的字符串取出来
2.把二维数组buf2的字符取出来
3.上面的字符串放在p3,p3是在堆区分配的二维内存
4.对p3中字符串进行排序,通过strcmp()进行排序
参数:
p1:指针数组首地址,char *p1[] = { "aa", "ccccccc", "bbbbbb" };
len1:p1元素个数
buf2:二维数组首元素地址,char buf2[10][30] = { "111111", "3333333", "222222" };
len2:buf2字符串的行数
p3:二级指针的地址,需要在函数内分配二维内存,保存p1和buf2的字符串,还需要排序
len3:保存p3中的字符串个数
返回值:
*/
//int sort(char **array1, int num1, char(*array2)[30], int num2,char ***myp3 /* out*/, int*num3)
/*
int ret = 0;
char *p1[] = { "aa", "ccccccc", "bbbbbb" };
char buf2[10][30] = { "111111", "3333333", "222222" };
char **p3 = NULL;
int len1, len2, len3, i = 0;
len1 = sizeof(p1) / sizeof(*p1);
len2 = sizeof(buf2)/sizeof(buf2[0]);
*/
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string.h>
int sort(char **array1, int num1, char(*array2)[30], int num2, char ***myp3 /* out*/, int*num3)
{
if (array1==NULL||array2==NULL||myp3==NULL||num3==NULL)
{
return -1;
}
char **buf ;
buf= (char**)malloc(sizeof(char *)* (num1+num2));
if (buf == NULL)
{
return -2;
}
for (int i = 0; i < (num1+num2); i++)
{
buf[i] = (char*) malloc(sizeof(char)*30);
if (buf[i] == NULL)
{
return -3;
}
}
for (int i = 0;i<num1;i++)
{
//buf[i] = array1[i];
strcpy(buf[i], array1[i]);
}
for (int j = 0; j < num2; j++)
{
strcpy(buf[num1 + j], array2[j]);
//buf[num1 + j] = array2[j];
}
for (int i = 0; i < num1 + num2; i++)
{
for (int j = i+1; j < num1 + num2; j++)
{
if (strcmp(buf[i],buf[j])>0)
{
char *tmp = buf[i];
buf[i] = buf[j];
buf[j] = tmp;
}
}
}
*num3 = num1 + num2;
*myp3 = buf;
return 0;
}
int main(void)
{
int ret = 0;
char *p1[] = { "aa", "ccccccc", "bbbbbb" };
char buf2[][30] = { "111111", "3333333", "222222" };
char **p3 = NULL;
int len1=NULL, len2=NULL, len3 = NULL, i = 0;
len1 = sizeof(p1) / sizeof(*p1);
len2 = sizeof(buf2)/sizeof(buf2[0]);
ret = sort(p1, len1, buf2, len2, &p3, &len3);
for (int i = 0; i < len3;i++)
{
printf("%s\n", p3[i]);
}
for (int i = 0; i < len3; i++)
{
if (p3[i] != NULL)
{
free(p3[i]);
p3[i] = NULL;
}
}
if (p3 != NULL)
{
free(p3);
p3 = NULL;
}
system("pause");
return 0;
}
将2个字符串数组连接之后进行排序
最新推荐文章于 2021-11-19 03:56:49 发布