【问题标题】:issue with qsort in cc中的qsort问题
【发布时间】:2015-03-25 06:25:04
【问题描述】:

我有这样的结构:

typedef struct item{
    char label[10];
    int support;
};

我创建了一个这样的结构数组:

struct item* finstr = (struct item*)malloc(sizeof(struct item)*10);

我用适当的值填充了数组,并希望使用 qsort 函数根据 'support' 的值对数组进行排序。但是,数组根本没有排序。输出与输入相同。

这是对 qsort 函数的调用和“比较器”函数的代码:

qsort((void*)finstr,(sizeof(finstr)/sizeof(finstr[0])),sizeof(finstr[0]),comparator);

比较函数:

int comparator(const void* i1,const void* i2) {
    int l = ((struct item*)i1)->support;
    int r = ((struct item*)i2)->support;
    return l-r;
}

我不明白我在哪里犯了错误。任何帮助是极大的赞赏。

提前致谢。

【问题讨论】:

  • sizeof(finstr) 是指针 finstr 的大小,而不是指针引用的内存量。
  • 另外,第一个 typedef 不应该编译 imo(它缺少名称)
  • 不要在比较中使用减法 (L-R) 技巧。当 L 为大正数且 R 为大负数时,您可能会遇到问题。结果可能是否定的。

标签: c arrays sorting qsort


【解决方案1】:

除非finstr 是一个数组,否则表达式(sizeof(finstr)/sizeof(finstr[0])) 不会给出元素的数量。在您的情况下,它的计算结果为sizeof(void*)/sizeof(struct item),很可能是0

将其替换为10

@ForhadAhmed 的出色建议:

10 中的malloc(sizeof(struct item)*10) 和传递给qsort 函数的数组大小替换为宏或变量是一种很好的做法,这样您就不会意外调用具有不同大小的qsort数组超出了您的预期。

【讨论】:

  • 在 'malloc(sizeof(struct item)*10)' 中替换 '10' 和传递给 qsort 函数的数组大小是一种很好的做法(如上面的修正中所建议的) ) 使用宏或变量,这样您就不会意外地使用与预期大小不同的数组调用 qsort
【解决方案2】:

尝试构建并运行以下命令,看看你得到什么答案:

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

typedef struct {
    char bar[123];
    int baz;
} foo;

int main(int argc, char** argv) {
    foo *foo_ptr = malloc(sizeof(foo) * 1000);
    fprintf(stdout, "%zu\n", sizeof(foo_ptr));
    fprintf(stdout, "%zu\n", sizeof(foo_ptr[0]));
    free(foo_ptr);
    return 0;
}

根据架构,您可能会注意到 sizeof(foo_ptr) 是 8 个字节 — 称为 foo_ptrfoo 指针的大小。将此与sizeof(foo_ptr[0]) 的值进行比较。这应该会提示哪里出了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2011-03-20
    • 2015-09-27
    • 2013-04-03
    • 2011-04-22
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多