2

我尝试使用 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);

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

4

3 回答 3

10

我已将您的 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
于 2013-02-21T02:17:47.190 回答
4

qsort(input, stringLen, sizeof (char*), myCompare) calls myCompare to compare strings which are sorted.

myCompare gets pointers to compared values. In our case we get pointers to strings (const char**). So we should compare *(const char**)a and *(const char**)b, which are strings pointed by a and b.

于 2015-05-24T09:57:41.590 回答
2

开始调试:

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

  printf("Comparing %s vs. %s for result %d\n", pa, pb, strcmp(pa,pb));

  return strcmp(pa,pb);
}

我想不久之后,你就会发现问题所在。:)

于 2013-02-21T02:05:36.043 回答