【发布时间】:2014-09-13 21:17:06
【问题描述】:
这是代码: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 的工作方式。我们有“typedef int”,而“(compfn)(const void, const void*)”这部分我真的不明白。
并且不应该(compfn)compare是compare(compfn)吗?为什么函数 compare 前面没有任何参数?
我检查了 wiki,唯一的例子是 C++,我将在 C 之后开始 C++。在这里也没有找到太多。
提前致谢。
编辑:我看你们不太活跃,我会睡一觉,明天试着理解它。之后我可能会做一个教程。
【问题讨论】:
-
它的typedef将函数的类型定义为指针。
标签: c