2014-10-30 140 views
0

您好我一直在寻找stackoverflow,我真的在挣扎函数指针作为参数。函数指针作为参数在C

我具有以下结构:

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); 
    } 
} 

(上面的内容可以是不正确的,我还没有真正与真正的selectionsort函数鬼混)。

当我在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; 
} 

注:该功能在前面加上包含了结构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 *)给出。

回答

2

在您的来电selectionsort你其实调用这些函数指针,从而导致您通过这些的结果致电selectionsort。它们是正常变量,应该像任何其他变量参数一样传递给selectionsort

但是,你实际上并不需要的变量,你可以直接传递功能:

selectionsort(&compare, &swap, argc); 

需要注意的是运营商,地址并不是必需的,但我更喜欢明确地使用它们告诉读者,我们通过指针这些功能。

3

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

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

这同样适用于swapData

(指针RESP它。)只是传递函数本身:

selectionsort(compareData, swapData, argc); 
+3

swapData ... – 2014-10-30 08:35:43

+1

@Andreas Compoletely正确的,我错过了... – glglgl 2014-10-30 08:37:00

+0

谢谢!我觉得没有发现有点傻,但无论你的及时答复是非常感激。 – thyde 2014-10-30 08:40:49