我需要对作为输入的字符串数组进行排序。 请帮我指点一下。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b){
char* s1 = (char*)a, s2 = (char*)b;
int len1 = strlen(s1), len2 = strlen(s2);
int i=0;
for(i=0; i< len1 && i<len2; i++){
if(s1[i] > s2[i]) return 1;
if(s1[i] < s2[i]) return 0;
}
return 0;
}
int main() {
int i;
int len;
scanf("%d",&len);
char* a[len];
for(i=0; i<len; i++){
a[i] = (char*)malloc(13);
scanf("%s",a[i]);
}
qsort(&a, len, sizeof(char*), compare);
for(i=0; i<len; i++){
printf("%s\n",a[i]);
}
return 0;
}
问题仅出在比较函数上。
最佳答案
char* s1 = (char*)a, s2 = (char*)b;
将 s1
声明为指针,将 s2
声明为 char,因为 *
绑定(bind)到右边的变量,而不是右边的类型左边。你需要写:
char *s1 = *((char**)a), *s2 = *((char**)b);
因此,编译器应该给你一堆关于 s2
的警告和错误。当我尝试编译您的代码时,我得到:
testsort.c: In function 'compare':
testsort.c:6: warning: initialization makes integer from pointer without a cast
testsort.c:7: warning: passing argument 1 of 'strlen' makes pointer from integer without a cast
testsort.c:10: error: subscripted value is neither array nor pointer
testsort.c:11: error: subscripted value is neither array nor pointer
通过这些更正,程序可以干净地编译并正确运行:
$ ./testsort
5
abc
12345
foo
aaa
bbb
输出:
12345
aaa
abc
bbb
foo
关于c - qsort比较功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19558447/