【问题标题】:qsort comparison function not workingqsort比较功能不起作用
【发布时间】:2013-11-02 17:14:48
【问题描述】:

我需要对一个字符串数组进行排序,作为输入。 请帮我指点这里。

 #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;
}

问题仅在于比较功能。

【问题讨论】:

  • if(s1[i] &lt; s2[i]) return 0; 应该是 if(s1[i] &lt; s2[i]) return -1;。另请注意,aaa 将与 aaax 与当前的比较方法进行比较。
  • compare() 函数的大部分应该只是对strcmp() 的调用。麻生太郎,don't cast the return value of malloc() 在 C 中。
  • qsort() 的比较器应该返回它 &lt;0 如果左/右元素升序排序,0 如果它们相等,&gt;0 如果它们降序排序。我认为你不能只返回10。我提到这一点是因为您的问题在相关搜索结果中的排名很高。

标签: c string sorting pointers


【解决方案1】:
char* s1 = (char*)a, s2 = (char*)b;

s1 声明为指针,将s2 声明为char,因为* 绑定到右侧的变量,而不是左侧的类型。你需要写:

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

【讨论】:

    【解决方案2】:

    您的数据数组是一个 char * 数组,因此比较方法由 qsort 传递“指向指针的指针”(char**)。

    你需要:

    char *s1 = *((char**)a), *s2 = *((char**)b);
    

    【讨论】:

    • 你说的是可以理解的,但char *s1 = (char*)a, *s2 = (char*)b 工作得很好。
    • +1,这当然是正确的。不过,从参数中删除 const 毫无意义。
    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 2014-10-10
    相关资源
    最近更新 更多