【发布时间】:2023-03-21 02:37:01
【问题描述】:
我想对 struct 数组进行排序,但是在理解比较函数的逻辑时,我感到困惑的是,当它在不传递参数的情况下调用 qsort() 函数时,比较函数是如何工作的
在 Windows 上的代码块上使用 GCC:
代码
int compare(const void * a, const void * b);
struct cricketers
{
int avrun;
char name[30];
int age;
int notm;
}india[Max] = {
122, "Sachin Tendulkar", 30, 67,
97, "Virendra Sehwag", 35, 56,
66, "Irfan Pathan", 32, 45,
153, "Yusuf Pathan", 36, 21,
101, "Yuvaraj Singh", 32, 45,
};
int main()
{
int i;
qsort(india, 5, sizeof(struct cricketers), compare);
for (i = 0; i < 5; i++)
{
printf("Name : %s", india[i].name);
printf("\nAge : %d", india[i].age);
printf("\nTotal Test Matches played : %d", india[i].notm);
printf("\nAverage Run : %d\n\n\n", india[i].avrun);
}
_getch();
return 0;
}
int compare(const void * a, const void * b)
{
return (*(int*)a - *(int*)b);
}
【问题讨论】:
-
qsort函数在内部调用compare并将正确的参数传递给它。但是,您实现compare的方式,如果您以这种方式使用它,您会得到未定义的行为。 -
compare函数传递了两个指针,它们必须转换为指向struct cricketers的指针。然后,您可以比较结构的成员。通常,您应该比较数据,而不是减去它,以防止溢出。看起来您试图通过利用您要比较的成员是struct中的第一个成员来走捷径。这是一种糟糕的做法。 -
@Blaze 请解释更多
-
如果我写变量=比较;这是什么意思
-
这是一个回调函数。它被
qsort而不是你调用。
标签: c sorting comparison quicksort qsort