[英]Using qsort() inside of struct with array of structs does not access the right elements but 0
我有以下2個結構:
typedef struct {
char fullName[40];
int yearOfBirth;
} Ancestor;
typedef struct {
Ancestor **ancestor;
int capacity;
int size;
} AncestorList;
我想按yearOfBirth
對數組中的Ancestor
元素進行排序。 這是我如何調用qsort():
qsort(listOfGreatUncles->ancestor, listOfGreatUncles->size, sizeof(Ancestor), compare); //listOfGreatUncles is a AncestorList struct
這是我的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);
}
}
現在我的a1和a2的輸出為0。我在做什么錯?
數組中的元素類型為Ancestor *
,這就是您應將其用作sizeof
的操作數。 提供給比較函數的指針是轉換為void *
的元素類型的指針,因此您將其轉換回Ancestor **
並取消引用。
qsort(listOfGreatUncles->ancestor, listOfGreatUncles->size, sizeof (Ancestor *), compare);
或如果正確輸入數組本身,則始終提供正確大小的形式:
qsort(listOfGreatUncles->ancestor,
listOfGreatUncles->size,
sizeof listOfGreatUncles->ancestor[0],
compare);
即
qsort(array, length, sizeof array[0], compfunc);
最后
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);
}
並且返回值實際上應該是
return (a1->yearOfBirth > a2->yearOfBirth) - (a1->yearOfBirth < a2->yearOfBirth);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.