c - qsort比较功能不起作用

标签 c string sorting pointers

我需要对作为输入的字符串数组进行排序。 请帮我指点一下。

 #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/

相关文章:

c - 使用gcc直接编译成机器码,无需链接

c - 为什么我用scanf时空格和回车不一样?

c# - 如何判断 Request.Form 中的值是否为数字? (C#)

c - 类似于 strstr 的高效版本

c - Valgrind 报告可能的堆栈溢出 - 这是什么意思?

c - Trie在c中的实现

PHP 从行中获取第一个单词

arrays - 在 Swift 中对数组进行分组和排序

javascript - 测试特定用例后减少没有初始值的空数组

c - 在 C 中对结构数组进行排序