问题描述
- C语言:用qsort()和strcmp实现对字符串数组的字典序排序
-
#include
#include
#include
int mycomp(const void p1,const void *p2)
{
const char *a1=(const char)p1;
const char a2=(const char)p2;
return strcmp(a1,a2);
}
int main()
{
int i;
char a[5]={"ssioo","abcde","bcade","bacd","jjjjj"};
qsort(a,5,sizeof(char),mycomp);
for(i=0;i<5;i++)
{
printf("%s ",a[i]);
}return 0;
}
warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]|
输出结果是没有经过排序的
问:要如何修改?要实现字符串数组字典序排序有什么思路?
解决方案
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int mycomp(const void* a,const void* b)
{
return strcmp(*(char **)a,*(char**)b);
}
int main()
{
char a[5][20] = {"ssioo","abcde","bcade","bacd","jjjjj"};
char** s = (char **)new char[20];
for(int i = 0; i < 5; i++)
{
s[i] = new char[20];
strcpy(s[i], a[i]);
}
qsort(s, 5, sizeof(char *), mycomp);
for(int i = 0; i < 5; i++)
printf("%sn", s[i]);
return 0;
}
输出
abcde
bacd
bcade
jjjjj
ssioo
解决方案二:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int mycomp(const void* a,const void* b)
{
return strcmp(*(char **)a,*(char**)b);
}
int main()
{
char *a[] = {"ssioo","abcde","bcade","bacd","jjjjj"};
qsort(a, 5, sizeof(char *), mycomp);
for(int i = 0; i < 5; i++)
printf("%sn", a[i]);
return 0;
}
解决方案三:
const char *a1=(const char)p1;
const char a2=(const char)p2;//这些都是类型不匹配
时间: 2024-10-06 02:18:27