c - qsort 没有对字符串数组进行排序

标签 c

<分区>

我尝试使用 qsort 对字符串数组进行排序。这是我的数组的内容:

{"a","orange","apple","mobile","car"}

这就是我使用 qsort 的方式:

int myCompare (const void * a, const void * b ) {
  const char *pa = (const char*)a;
  const char *pb = (const char*)b;
  return strcmp(pa,pb);
}

int stringLen = sizeof(input)/sizeof(char *);
qsort(input, stringLen, sizeof (char*), myCompare);

但是,当我打印数组时,没有任何改变。这有什么问题吗?

最佳答案

我已将您的 myCompare 函数更改为 Mitch Wheat 之前发布的函数,并且可以正常工作。这是示例:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int myCompare (const void * a, const void * b ) {
    const char *pa = *(const char**)a;
    const char *pb = *(const char**)b;

    return strcmp(pa,pb);
}

int main() {
    int i;
    const char *input[] = {"a","orange","apple","mobile","car"};

    int stringLen = sizeof(input) / sizeof(char *);
    qsort(input, stringLen, sizeof(char *), myCompare);

    for (i=0; i<stringLen; ++i)
        printf("%d: %s\n", i, input[i]);
}

这将返回:

0: a
1: apple
2: car
3: mobile
4: orange

关于c - qsort 没有对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14993282/

相关文章:

android - 我需要在 Android Studio 中构建 NDK。但它返回错误

c++ - gcc - 使用 #pragma 将 __attribute__((section (".dflash_code"))) 应用于整个源文件

c++ - 专家的字符串和字符映射问题

c - 自 “The C Programming Language” 以来发生了什么变化

c - 如何在C中打印带有正确符号的等式

c - 声明为 void* foo() 的函数

c - 在 C 中使用 libxml 进行 XML 解析不显示属性名称

c - C 中的 Putchar 和 Getchar

c++ - 用 C/C++ 语言编写低延迟代码,自动处理缓存行大小

c - 末尾显示随机字符的数组