qsort行为怪异,怎么了?

时间:2019-09-25 19:23:08

标签: c sorting c-strings string-literals qsort

下面的代码为什么不对月份名称进行排序?基址正确,元素数目正确,每个元素的大小正确,cmp函数正确。 gcc -W -Wall -ansi -pedantic不会抱怨窥视。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int by_name(const void *a, const void *b) {
    fprintf(stderr, "%p %p\n", a, b);
    return strcmp((const char *)a, (const char *)b);
}
int main(void) {
    char *months[] = {
        "January",
        "Februar",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    };
    unsigned n;

    qsort(months, sizeof months / sizeof *months, sizeof *months,
        by_name);
    for (n = 0; n < sizeof months / sizeof *months; ++n) {
        fprintf(stderr, "%d %p %s\n", n, months[n], months[n]);
    }
    return 0;
}

我添加了一些代码来查看qsort实际在做什么,这就是结果。我们看到qsort传递给比较函数的地址与实际数组数据完全不同。怎么了?

我已经使用qsort多次,主要是对各种结构进行排序,但从来没有像这样原始的东西(我需要解码一些真正愚蠢的datetime字符串)。

0x1ffeffffb8 0x1ffeffffc0
0x1ffeffffb0 0x1ffeffffb8
0x1ffeffffd0 0x1ffeffffd8
0x1ffeffffc8 0x1ffeffffd0
0x1ffeffffb0 0x1ffeffffc8
0x1ffeffffb8 0x1ffeffffc8
0x1ffeffffc0 0x1ffeffffc8
0x1ffeffffe8 0x1ffefffff0
0x1ffeffffe0 0x1ffeffffe8
0x1fff000000 0x1fff000008
0x1ffefffff8 0x1fff000000
0x1ffeffffe0 0x1ffefffff8
0x1ffeffffe8 0x1ffefffff8
0x1ffefffff0 0x1ffefffff8
0x1ffeffffb0 0x1ffeffffe0
0x1ffeffffb8 0x1ffeffffe0
0x1ffeffffc0 0x1ffeffffe0
0x1ffeffffc8 0x1ffeffffe0
0x1ffeffffd0 0x1ffeffffe0
0x1ffeffffd8 0x1ffeffffe0
0 0x10a00b January
1 0x10a013 Februar
2 0x10a01b March
3 0x10a021 April
4 0x10a027 May
5 0x10a02b June
6 0x10a030 July
7 0x10a035 August
8 0x10a03c September
9 0x10a046 October
10 0x10a04e November
11 0x10a057 December

1 个答案:

答案 0 :(得分:10)

在比较函数中使用以下return语句

return strcmp( *(const char ** )a, *(const char **)b );

比较函数获取指向具有指针类型的数组元素的指针。

还要注意,对于无符号变量n,应使用格式转换说明符%u

这是您更新的程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int by_name(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}
int main(void) {
    char *months[] = {
        "January",
        "Februar",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    };
    unsigned n;

    qsort(months, sizeof months / sizeof *months, sizeof *months,
        by_name);
    for (n = 0; n < sizeof months / sizeof *months; ++n) {
        printf("%u %p %s\n", n, months[n], months[n]);
    }
    return 0;
}

其输出可能看起来像

0 0x56490a5b001a April
1 0x56490a5b002e August
2 0x56490a5b0050 December
3 0x56490a5b000c Februar
4 0x56490a5b0004 January
5 0x56490a5b0029 July
6 0x56490a5b0024 June
7 0x56490a5b0014 March
8 0x56490a5b0020 May
9 0x56490a5b0047 November
10 0x56490a5b003f October
11 0x56490a5b0035 September