[英]Using qsort() inside of struct with array of structs does not access the right elements but 0
I have the following 2 structs: 我有以下2个结构:
typedef struct {
char fullName[40];
int yearOfBirth;
} Ancestor;
typedef struct {
Ancestor **ancestor;
int capacity;
int size;
} AncestorList;
and I would like to sort the Ancestor
elements os the array by yearOfBirth
. 我想按
yearOfBirth
对数组中的Ancestor
元素进行排序。 Here is how I call qsort(): 这是我如何调用qsort():
qsort(listOfGreatUncles->ancestor, listOfGreatUncles->size, sizeof(Ancestor), compare); //listOfGreatUncles is a AncestorList struct
and here is my compare
procedure: 这是我的
compare
过程:
int compare(const void *s1, const void *s2) {
Ancestor *a1 = (Ancestor *)s1;
Ancestor *a2 = (Ancestor *)s2;
printf("a1 yearOfBirth %d\n", a1->yearOfBirth);
printf("a2 yearOfBirth %d\n", a2->yearOfBirth);
return (a1->yearOfBirth - a2->yearOfBirth);
}
}
Now my output for a1 and a2 are 0. What am I doing wrong? 现在我的a1和a2的输出为0。我在做什么错?
The elements in the array are of type Ancestor *
and that's what you should use as the operand to sizeof
. 数组中的元素类型为
Ancestor *
,这就是您应将其用作sizeof
的操作数。 The pointers given to the comparison function are pointers to the element type cast to void *
, hence you cast them back to Ancestor **
and dereference. 提供给比较函数的指针是转换为
void *
的元素类型的指针,因此您将其转换回Ancestor **
并取消引用。
qsort(listOfGreatUncles->ancestor, listOfGreatUncles->size, sizeof (Ancestor *), compare);
or the form that always gives the right size if the array itself is properly typed: 或如果正确输入数组本身,则始终提供正确大小的形式:
qsort(listOfGreatUncles->ancestor,
listOfGreatUncles->size,
sizeof listOfGreatUncles->ancestor[0],
compare);
ie 即
qsort(array, length, sizeof array[0], compfunc);
And finally 最后
int compare(const void *s1, const void *s2) {
Ancestor *a1 = *(Ancestor **)s1;
Ancestor *a2 = *(Ancestor **)s2;
printf("a1 yearOfBirth %d\n", a1->yearOfBirth);
printf("a2 yearOfBirth %d\n", a2->yearOfBirth);
return (a1->yearOfBirth - a2->yearOfBirth);
}
And the return value should actually be 并且返回值实际上应该是
return (a1->yearOfBirth > a2->yearOfBirth) - (a1->yearOfBirth < a2->yearOfBirth);
to avoid undefined behaviour on extreme values of int
. 避免对
int
极值进行不确定的行为 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.