使用 qsort() 对组合结构进行排序
Sort composed structs using qsort()
我有以下结构。 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;
我想使用 qsort
按 dni
排序。我正在尝试使用以下代码:
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)
给你整个数组的大小。
你need/want是一个元素的大小。
要做到这一点
sizeof(*discountsShop->discounts)
或
sizeof(discountsShop->discounts[0])
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.
您传递的是整个数组的大小,而不是每个元素的大小。
sizeof(discountsShop->discounts)
应该是
sizeof(discountsShop->discounts[0])
我有以下结构。 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;
我想使用 qsort
按 dni
排序。我正在尝试使用以下代码:
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)
给你整个数组的大小。
你need/want是一个元素的大小。
要做到这一点
sizeof(*discountsShop->discounts)
或
sizeof(discountsShop->discounts[0])
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.
您传递的是整个数组的大小,而不是每个元素的大小。
sizeof(discountsShop->discounts)
应该是
sizeof(discountsShop->discounts[0])