c中的qsort问题

issue with qsort in c

我有这样的结构:

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

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

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

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

这里是对 qsort 函数的调用和 'comparator' 函数的代码:

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;
}

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

提前致谢。

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

替换为10

来自@ForhadAhmed 的极好的建议:

Its good practice to replace the 10 in malloc(sizeof(struct item)*10) and the size of the array passed to the qsort function with a macro or a variable so that you don't accidentally call qsort with a different sized array than what you intended.

尝试构建和运行以下内容,看看您得到什么答案:

#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) 是八个字节 — 称为 foo_ptrfoo 指针的大小。将其与 sizeof(foo_ptr[0]) 的值进行比较。这应该会提示哪里出了问题。