解释qsort库中使用的函数的typedef

我正在使用qsort库函数对结构元素数组进行排序,而在Internet上搜索时我找到了一个资源: INFO:使用C qsort()函数 @support.microsoft 对结构进行排序 。

我知道qsort函数需要通用指针进行类型转换。

但是我无法得到这一行:

typedef int (*compfn) (const void*, const void*); 

已经宣布的,以及随后的电话:

 qsort((void *) &array, // Beginning address of array 10, // Number of elements in array sizeof(struct animal), // Size of each element (compfn)compare // Pointer to compare function ); 
  1. typedef是如何表现的,我的意思是我们究竟有什么类型的intdeffed int (*compfn)int (compfn)
  2. 如果是前者,那么不应该调用(*compfn)

句法:

 typedef int (*compfn) (const void*, const void*); ^ ^ ^ ^ ^ | return type | arguments type | new type name defining new type 

compfn是由typedef关键字定义的新用户定义type

所以,你有正确的typedefded int (*)(const void*, const void*); 使用我上面描述的语法来comfn

声明:

  compfn fun; // same as: int (*fun) (const void*, const void*); 

表示fun是一个函数指针,它接受const void* types的两个参数并返回int

假设你有一个像这样的函数:

 int xyz (const void*, const void*); 

然后你可以将xyz地址分配给fun

 fun = &xyz; 

在调用qsort()

在表达式(compfn)compare一个函数compare (compfn)类型函数。

一个疑问:

呼叫不应该是(*compfn)

不,它的类型名称不是函数名称。

注意 :如果你只是写int (*compfn) (const void*, const void*); 如果没有typedef,那么comfn将是一个指向函数的指针,该函数返回int并获取两个类型为const void*参数const void*

typedef声明为特定类型创建别名 。 这意味着它可以在声明和定义中用作任何其他类型。

所以,如果你有例如

 typedef int (*compfn)(const void*, const void*); 

然后,您可以仅使用compfn而不是整个函数指针声明来声明变量或参数。 例如,这两个声明是相同的:

 compfn function_pointer_1; int (*function_pointer_2)(const void*, const void*); 

两者都创建了一个函数指针变量,唯一的区别是变量名称的名称。

当你有长和/或复杂的声明时,使用typedef是很常见的,这样可以轻松编写这样的声明并使其更易于阅读。

它是一种函数指针。 被指向的函数返回int并接受两个const void*参数。