繁体   English   中英

qsort比较功能不起作用

[英]qsort comparison function not working

我需要对字符串数组进行排序,以作为输入。 请帮我在这里的指示。

 #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,因为*绑定到右侧的变量,而不是左侧的类型。 您需要写:

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

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

你需要:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM