的qsort比较函数不工作 [英] qsort comparison function not working
本文介绍了的qsort比较函数不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要排序字符串数组,作为输入。
帮我指点这里请。
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;INT比较(常量无效*一,常量无效* B){
字符* S1 =(字符*)一,S2 =(字符*)B:
INT LEN1 = strlen的(S1),LEN2 = strlen的(S2);
INT I = 0;
对于(i = 0; I<&LEN1功放;&安培; I< LEN2;我++){
如果(S1 [Ⅰ]≥S2 [I])返回1;
如果(S1 [1] - ; S2 [I])返回0;
}
返回0;
}诠释主(){
INT I;
INT LEN;
scanf函数(%d个,&安培; LEN);
字符* A [LEN];
对于(i = 0; I< LEN,我++){
一个由[i] =(字符*)malloc的(13);
scanf函数(%S,一个[我]);
}
的qsort(安培;一,LEN,sizeof的(字符*),比较);
对于(i = 0; I< LEN,我++){
的printf(%S \\ n,一个[我]);
} 返回0;
}
问题是只比较功能。
解决方案
的char * S1 =(字符*)一,S2 =(字符*)B:
声明 S1
作为一个指针和 S2
为一个char,因为 *
结合至该变量在右侧,而不是左侧的类型。你需要写:
的char * S1 = *((字符**)一),* S2 = *((字符**)B);
编译器应该给你一堆警告和错误的约 S2
因为这个原因。当我试图编译code,我得到了:
testsort.c:在功能比较:
testsort.c:6:警告:初始化将指针整数,未作投
testsort.c:7:警告:传递的'strlen的'参数1,使指针从整数没有投
testsort.c:10:错误:下标值既不是数组,也不指针
testsort.c:11:错误:下标值既不是数组,也不指针
通过这些调整,该方案完全编译和运行正常:
$ ./testsort
五
ABC
12345
富
AAA
BBB
输出:
12345
AAA
ABC
BBB
富
I need to sort an array of strings, taken as input. Help me with the pointers here please.
#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;
}
The problem is with the compare function only.
解决方案
char* s1 = (char*)a, s2 = (char*)b;
declares s1
as a pointer and s2
as a char, because *
binds to the variable on the right, not to the type on the left. You need to write:
char *s1 = *((char**)a), *s2 = *((char**)b);
The compiler should have given you a bunch of warnings and errors about s2
because of this. When I tried to compile your code, I got:
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
With these correction, the program compiles cleanly and runs correctly:
$ ./testsort
5
abc
12345
foo
aaa
bbb
Output:
12345
aaa
abc
bbb
foo
这篇关于的qsort比较函数不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文