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

时间:2013-07-22 08:09:33

标签: c pointers function-pointers typedef qsort

我正在使用qsort库函数对结构元素数组进行排序,而在Internet上搜索时我找到了一个资源:INFO: Sorting Structures with the C qsort() Function @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的行为方式,我的意思是我们确实在哪里输入int (*compfn)int (compfn)
  2. 如果是前者,那么呼叫应该不是(*compfn)

3 个答案:

答案 0 :(得分:8)

语法:

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

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

因此,您使用上面描述的语法确切地将int (*)(const void*, const void*);命名为comfn

声明:

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

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

假设您有以下功能:

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

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

fun = &xyz; 

致电qsort()

在表达式(compfn)compare中,您将类型函数compare类型转换为(compfn)

怀疑:

  

呼叫不应该是(*compfn)

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

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

答案 1 :(得分:2)

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

所以如果你有例如。

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

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

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

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

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

答案 2 :(得分:0)

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