解释的typedef在的qsort库中使用函数 [英] Explain typedef for function used in qsort library
问题描述
我使用的qsort库函数来排序的结构元素的数组,而在互联网上搜索,我发现一个资源:的 INFO:排序结构与C的qsort()函数 @ support.microsoft
据我了解,qsort函数需要由通用指针的类型强制转换。
但是我不能够得到这个行:
的typedef INT(* compfn)(常量无效*,常量无效*);
已宣布,其后续调用:
的qsort((无效*)及阵列,//开始数组的地址
10,//在数组元素的数量
的sizeof(结构动物),//每个元件的尺寸
(compfn)比较//指针比较功能
);
- 如何为
的typedef
表现,我的意思是到底有没有我们typedeffedINT(* compfn)
或INT(compfn)
? - 如果是前者,则不宜电话是
(* compfn)
?
语法:
的typedef INT(* compfn)(常量无效*,常量无效*);
^ ^ ^ ^ ^
|返回类型|参数类型
|新的类型名称
定义新类型
compfn
是定义一个新用户的 键入
的定义为的typedef
关键字
所以,你必须精确地typedefded INT(*)(常量无效*,常量无效*);
到 comfn
。
的声明:
compfn乐趣; //一样:INT(*有趣)(常量无效*,常量无效*);
办法乐趣
是一个函数指针采用常量无效*
类型并返回<$ C $的两个参数C> INT 。
假设你有一个像功能:
INT XYZ(常量无效*,常量无效*);
然后你可以分配 XYZ
地址乐趣
。
乐趣=安培; XYZ;
在调用的qsort()
:
在EX pression (compfn)比较
,你是类型转换函数比较
到(compfn)
输入功能。
一个疑问:
应该不是电话是
(* compfn)
。
块引用>没有,它的类型名称不是函数名。
注意:如果你只是写
INT(* compfn)(常量无效*,常量无效*);
没有的typedef那么comfn
将是一个指针,返回的函数INT
,并采取类型的两个参数常量无效*
I am using qsort library function to sort an array of structure elements, while searching on the Internet I found a resource: INFO: Sorting Structures with the C qsort() Function @ support.microsoft.
I understand that qsort function requires to be typecast by generic pointers.
However I am not able to get this line:
typedef int (*compfn) (const void*, const void*);
Which has been declared, and its subsequent call:
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 );
- How is
typedef
behaving, I mean what exactly have we typedeffedint (*compfn)
orint (compfn)
?- If the former, then shouldn't the call be
(*compfn)
?
解决方案Syntax:
typedef int (*compfn) (const void*, const void*); ^ ^ ^ ^ ^ | return type | arguments type | new type name defining new type
compfn
is a new user definedtype
defined bytypedef
keyword,So, you have exactly typedefded
int (*)(const void*, const void*);
tocomfn
using the syntax I described above.A declaration:
compfn fun; // same as: int (*fun) (const void*, const void*);
means
fun
is a function pointer that takes two arguments ofconst void*
types and returnsint
.Suppose you have a function like:
int xyz (const void*, const void*);
then you can assign
xyz
address tofun
.fun = &xyz;
At calling
qsort()
:In expression
(compfn)compare
, you are typecasting a functioncompare
to(compfn)
type function.A doubt:
shouldn't the call be
(*compfn)
.No, its type name not function name.
Note: if you just writing
int (*compfn) (const void*, const void*);
without typedef thencomfn
will be a pointer to a function that returnsint
and take two arguments of typeconst void*
这篇关于解释的typedef在的qsort库中使用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!