gpt4 book ai didi

c - 函数指针作为C中的参数

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:25 27 4
gpt4 key购买 nike

您好,我一直在查看 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);
}
}

(上面的内容可能不正确,我还没有真正玩弄实际的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;
}

注意:函数 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 *) 给出了。

最佳答案

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

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

swapData 也是如此。

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

selectionsort(compareData, swapData, argc);

关于c - 函数指针作为C中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26648243/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com