qsort() - 比较函数参数

qsort() - compare function parameter

假设我有一个名为 Student.

的结构
typedef struct student {
    int age;
    char name[10];
} Student;

我有一组指向学生的指针。

Student *a[10];

我需要按学生姓名对数组进行排序。所以我写了比较函数:

int compare(const void *a, const void *b){
    Student *temp1=*(Student **)a;
    Student *temp2=*(Student **)b;
    return strcmp(temp1->name, temp2->name);
}

然后我有排序的功能:

void SortArray(Student *a[], int len){
    qsort(a, len, sizeof(Student *), *compare*);
    printArray(a);
}

qsort 的最后一部分是我没有得到的。我看到有些帖子他们写了 &compare,有些则没有。只有当我使用 &compare 时它才起作用。
我怎么知道是否使用&

您是否试过像这样调用函数:)

qsort(a, len, sizeof(Student *), ***********compare);

或喜欢

qsort(a, len, sizeof(Student *), &***********compare);

根据 C 标准(6.3.2.1 左值、数组和函数指示符)

4 A function designator is an expression that has function type. Except when it is the operand of the sizeof operator65) or the unary & operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’’.

所以在这个表达式中

***********compare

函数指示符 compare 被隐式转换为函数指针,然后应用取消引用,它又被转换为函数类型,然后再次转换为函数指针,依此类推。

当然你可以明确指定&compare虽然这不是必需的。

这是一个演示程序

#include <stdio.h>

void f(void)
{
    puts("Hello eitanmayer");
}

void g(void f(void))
{
    f();
}

int main( void )
{
    g(&******f);
}

它的输出是

Hello eitanmayer

所以您的代码的问题可能出在其他地方。

作为引用函数的函数名,可以使用函数名。另外,如评论中所述,& 也可以参考。