[英]qSort a Struct using Typedef with Casts, which totally confuses me
这是代码: http : //support.microsoft.com/kb/73853
/* Compile options needed: none
*
* This example program uses the C run-time library function qsort()
* to sort an array of structures.
*/
#include <stdio.h>
#include <stdlib.h>
typedef int (*compfn)(const void*, const void*);
struct animal { int number;
char name[15];
};
struct animal array[10] = { { 1, "Anaconda" },
{ 5, "Elephant" },
{ 8, "Hummingbird" },
{ 4, "Dalmatian" },
{ 3, "Canary" },
{ 9, "Llama" },
{ 2, "Buffalo" },
{ 6, "Flatfish" },
{ 10, "Zebra" },
{ 7, "Giraffe" } };
void printarray(void);
int compare(struct animal *, struct animal *);
void main(void)
{
printf("List before sorting:\n");
printarray();
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
printf("\nList after sorting:\n");
printarray();
}
int compare(struct animal *elem1, struct animal *elem2)
{
if ( elem1->number < elem2->number)
return -1;
else if (elem1->number > elem2->number)
return 1;
else
return 0;
}
void printarray(void)
{
int i;
for (i = 0; i < 10; i++)
printf("%d: Number %d is a %s\n",
i+1, array[i].number, array[i].name);
}
我不明白类型转换与强制转换的工作方式。 我们有“ typedef int”,而部分“( compfn)(const void ,const void *)”是我真正不了解的。
并且不应该(compfn)compare比较(compfn)吗? 为什么函数比较之前没有任何参数? 我检查了Wiki,唯一的例子是C ++,我将在C之后启动C ++。在这里也找不到很多。 提前致谢。 编辑:我看到你们不太活跃,我会睡一会儿,明天尝试去理解它。 我以后可能会做一个教程。
typedef int (*compfn)(const void*, const void*);
Return type: int
Argument 1: pointer
Argument 2: pointer
int compare(struct animal *, struct animal *);
Return type: int
Argument 1: pointer
Argument 2: pointer
如您所见,它们彼此兼容,C中的类型检查要弱一些。
当您键入(compfn)compare时,您告诉编译器切换到另一个函数签名,即左手装箱,在这种情况下确实匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.