【问题标题】:qSort a Struct using Typedef with Casts, which totally confuses meqSort a Struct using Typedef with Casts,这让我很困惑
【发布时间】: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


【解决方案1】:
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 时,你告诉编译器切换到另一个函数签名,左手装箱,在这种情况下确实匹配。

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多