K&R 5.11 函数指针 C 中的混淆线

Pru*_*uzo 5 c pointers casting function-pointers kernighan-and-ritchie

这行的最后一个参数main()让我迷失了

// declaration
void qsort(char *linep[], int left, int right, int (*compare)(void *, void*);

// use
main(){
    qsort((void**) lineptr, 0, nlines-1, (int (*)(void*,void*))(numeric ?
    numcmp : strcmp));
}
Run Code Online (Sandbox Code Playgroud)

我理解三元运算符,但让我们说 numeric == 0 那么这是什么意思?

(int (*)(void *, void*))strcmp;
Run Code Online (Sandbox Code Playgroud)

函数参数的数据类型是否不匹配?

int strcmp(const char*, const char*);
void qsort( , , , int(*)(void*)(void*);
Run Code Online (Sandbox Code Playgroud)

我可以对函数指针进行类型转换吗?

Sou*_*osh 5

在您的代码中,使用演员表

  (int (*)(void *, void*))strcmp;
Run Code Online (Sandbox Code Playgroud)

意味着,strcmp()是一个函数指针,它接受两个void *参数并返回一个int.

通常,对于函数指针,强制转换是一个非常糟糕的主意,引用自C11§6.3.2.3 章节

[...] 如果使用转换后的指针调用类型与引用类型不兼容的函数,则行为未定义。

但是,在您的情况下,对于参数类型,char *并且void *彼此别名,因此类型转换类型与实际有效类型兼容,因此(稍后)定义了函数调用。