【问题标题】:Function pointer as parameter in C函数指针作为C中的参数
【发布时间】:2014-10-30 08:32:11
【问题描述】:

您好,我一直在研究 stackoverflow,但我真的很想将函数指针作为参数。

我有结构:

 struct Node {
     struct Node *next;
     short len;
     char data[6];
 };

和功能:

 void selectionsort(int (*compareData)(struct Node *, struct Node *), void (*swapData)(struct Node *, struct Node *), int n);

 compare(struct Node *a, struct Node *b);
 swap(struct Node *a, struct Node *b);

选择排序仅用于调用比较和交换:

 void selectionsort(int compare(struct Node *a, struct Node *b), void swap(struct Node *a, struct Node *b), int n){
     int i;
     for (i = 0; i < n; i++){
         compare(a, b);
         swap(a, b);
     }
 }

(上面的内容可能不正确,我还没有真正使用实际的选择排序函数。

当我在 main 中调用 selectionsort 时出现问题。我的印象是这会起作用:

 int main(int argc, char **argv){
     int n;
     struct Node *list = NULL;
     for (n = 1; n < argc; n++)
         list = prepend(list, argv[n]); //separate function not given here.
     int (*compareData)(struct Node *, struct Node *) = compare; //not sure I needed to redeclare this
     void (*swapData)(struct Node *, struct Node *) = swap;
     selectionsort(compareData(list, list->next), swapData(list, list->next), argc);

     //other stuff
     return 0;
 }

注意:函数 prepend 包含结构的 malloc,因此已处理。

我遇到的问题是,无论我如何处理函数声明等,我总是会收到以下错误:

warning: passing argument 1 of 'selectionsort' makes pointer from integer without a cast [enabled by default]
note: expected 'int (*)(struct Node *, struct Node *)' but argument is of type 'int'.

任何帮助解释我收到此错误消息的原因以及如何解决它都将不胜感激。

我知道该函数需要一个函数指针,但我认为我上面的代码将允许调用 compare。任何输入将不胜感激,这也是一个作业(所以请帮助我避免作弊)并给出参数int(*compareData)(struct Node *, struct Node *) void (*swapData)(struct Node *, struct Node *)

【问题讨论】:

    标签: c pointers struct function-pointers


    【解决方案1】:

    selectionsort(compareData(list, list->next), swapData(list, list->next), argc);
    

    您正在传递调用函数compareData 的结果。这是错误的。

    swapData 也是如此。

    只需传递函数本身(或指向它的指针):

    selectionsort(compareData, swapData, argc);
    

    【讨论】:

      【解决方案2】:

      在您对selectionsort 的调用中,您实际上是在调用那些函数指针,导致您将这些调用的结果传递给selectionsort。它们是普通变量,应该像任何其他变量参数一样传递给selectionsort

      但是,您实际上并不需要变量,您可以直接传递函数:

      selectionsort(&compare, &swap, argc);
      

      请注意,并非严格需要地址运算符,但我更喜欢使用它们来明确地告诉读者我们正在将指针传递给这些函数。

      【讨论】:

        猜你喜欢
        • 2013-09-12
        • 1970-01-01
        • 2017-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多