在带有结构数组的结构内部使用 qsort() 不会访问正确的元素而是 0
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
对数组 os 中的 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 值实际上应该是
return (a1->yearOfBirth > a2->yearOfBirth) - (a1->yearOfBirth < a2->yearOfBirth);
避免.
我有以下 2 个结构:
typedef struct {
char fullName[40];
int yearOfBirth;
} Ancestor;
typedef struct {
Ancestor **ancestor;
int capacity;
int size;
} AncestorList;
我想按 yearOfBirth
对数组 os 中的 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 值实际上应该是
return (a1->yearOfBirth > a2->yearOfBirth) - (a1->yearOfBirth < a2->yearOfBirth);
避免