微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C: qsort() on struct array -- 返回垃圾

如何解决C: qsort() on struct array -- 返回垃圾

我想使用 qsort()函数对结构数组进行排序。 我已经彻底阅读了 man 3 qsort,并查阅了互联网上的其他资源,但没有成功。

我以为我已经确定 nmembsize 参数是正确的。

我还通过编写以下示例确保问题不是由我周围的代码引起的,而是来自我对 qsort() 的缺乏了解:

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

typedef struct example_structure {
    size_t a;
    size_t b;
} example_structure;

static int cmp_example_structure(const void *h1,const void *h2) {
    return (((example_structure *)h1)->a - ((example_structure *)h2)->a);
}

int main() {
    example_structure *example_structures = calloc(10,sizeof(example_structure));

    printf("sizeof(example_structures[0]) = %lu; sizeof(example_structure *) = %lu\n",sizeof(example_structures[0]),sizeof(example_structure *));

    fputc('\n',stdout);

    for(size_t h = 0; h < 10; h++) {
        example_structures[h].a = h;
        example_structures[h].b = h;
    }

    for(size_t h = 0; h < 10; h++) {
        printf("%ld ",example_structures[h].b);
    }

    fputc('\n',stdout);

    for(size_t h = 0; h < 10; h++) {
        printf("0x%lX ",stdout);
    fputc('\n',stdout);

    qsort(example_structures,10,cmp_example_structure);

    for(size_t h = 0; h < 10; h++) {
        printf("%ld ",stdout);

    free(example_structures);
}

我注意到返回的垃圾似乎被转移了:

0 1 2 3 4 5 6 7 8 9 
0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 

0 1 17179869184 6 34359738368 131072 1970346311811072 131072 1970324836974592 9 
0x0 0x1 0x400000000 0x6 0x800000000 0x20000 0x7000500000000 0x20000 0x7000000000000 0x9 

我该如何解决这个问题?

提前致谢。

解决方法

qsort(3): sort array - Linux man page 说:

.estimation-category

qsort() 函数使用大小为 size 的 nmemb 元素对数组进行排序。基本参数指向数组的开头。

如您所见,您应该将元素数量指定为第二个参数,将一个元素的大小指定为第三个参数。

换句话说,

void qsort(void *base,size_t nmemb,size_t size,int (*compar)(const void *,const void *));

应该

qsort(example_structures,sizeof(example_structures[0]),10,cmp_example_structure);
,

您有 sizenmemb 参数到 qsort 向后。您告诉它您正在尝试对每个大小为 10 的 sizeof(example_structures[0]) 个元素进行排序,而不是每个大小为 sizeof(example_structures[0]) 的 10 个元素。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。