gpt4 book ai didi

c - 使用 qsort() 对组合结构进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 05:34:32 27 4
gpt4 key购买 nike

我有以下结构。 tDiscountsShop 包含 5 个 tDiscount 结构。

#define MAXDISCOUNTS 50

typedef enum {FALSE, TRUE} bool;

typedef struct {

int dni;
float discount;
bool changed;

} tDiscount;

typedef struct {

tDiscount discounts[MAXDISCOUNTS];
int numDiscounts;

} tDiscountsShop;

我想使用 qsortdni 排序。我正在尝试使用以下代码:

int compare(const void *s1, const void *s2)
{
tDiscount *e1 = (tDiscount *)s1;
tDiscount *e2 = (tDiscount *)s2;

return e1->dni - e2->dni;
}


qsort (discountsShop->discounts, discountsShop->numDiscounts, sizeof(discountsShop->discounts), compare);

如果我能解释我做错了什么以及如何解决这个问题,我将不胜感激。提前致谢。

最佳答案

这个

sizeof(discountsShop->discounts)

为您提供整个数组的大小

您需要/想要的是一个元素的大小

为了做到这一点

sizeof(*discountsShop->discounts)

sizeof(discountsShop->discounts[0])

来自 qsort()'s documentation :

void qsort(void *base, size_t nel, size_t width,
int (*compar)(const void *, const void *));

[...] The size of each object, in bytes, is specified by the width argument.

关于c - 使用 qsort() 对组合结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43823197/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com