【发布时间】: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