c - 使用 Qsort 对 C 程序中的地址进行排序

标签 c sorting qsort

我正在尝试按内存地址对指针数组进行排序:

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

typedef struct flist {
    int size;
    struct flist *blink;
    struct flist *flink;
} *Flist;

int compare(const void *x, const void *y)
{
    Flist a = (Flist)x;
    Flist b = (Flist)y;

    if(a < b)
        return -1;
    else
        return 1;
}

int main()
{
    int a[] = {3, 1, 2, 4, 0};
    Flist b[5];
    int i;

    for(i = 0; i < 5; i++)
        b[a[i]] = (Flist)malloc(12);

    printf("Here is the array before sorting:\n");
    for(i = 0; i < 5; i++)
        printf("%p\n", b[i]);

    qsort(b, 5, sizeof(Flist), compare);

    printf("Here is the array after sorting:\n");
    for(i = 0; i < 5; i++)
        printf("%p\n", b[i]);
}

但是,程序对地址的顺序没有影响:

这是排序前的数组:
0x759090
0x759030
0x759050
0x759010
0x759070
这是排序后的数组:
0x759090
0x759030
0x759050
0x759010
0x759070

如有任何建议,我们将不胜感激!

最佳答案

您缺少一定程度的间接性:qsort 发送正在排序的元素的地址,而不是元素本身。

在您的情况下,您会看到正在传递的 Flist 元素的地址。您需要取消引用转换为Flist*(这是一个指向指针的指针)后传入的指针:

int compare(const void *x, const void *y) {
    Flist a = *((Flist*)x);
    Flist b = *((Flist*)y);

    if(a < b)
        return -1;
    else
        return 1;
}

关于c - 使用 Qsort 对 C 程序中的地址进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13114652/

相关文章:

sorting - 如何根据数值对 slice 进行排序,如果数值等于则按字母顺序排序

sorting - 如何按 map 的值对 slice 进行排序

python - 在 python 中使用 .csv 按特定列数据排序

c - 通用快速排序

c - qsort() 性能问题

c++ - “安全”DLL 注入(inject)

c - 如何为 TMS320F2812 DSP 编写内存屏障?

C - 将字符串保存到数组元素中

c - C语言三线程通信问题(出现死锁)

c - 使用 stdlib.c 中的 qsort() 根据每个 *char 中的第三个字母对 C 中的字符串数组进行排序