[英]Function pointer to a struct function pointer
今天,我收到了有关function pointer(binary tree)
。 有一大堆我不明白的代码...我了解一个function pointer
是什么以及它如何工作,但是大约有两个function pointers
( parameter
中有1个)
头文件
typedef struct _node_ {
int key;
struct _node_ *left;
struct _node_ *right;
} node;
typedef struct _bstree_ {
node *root_node;
int (*compare_keys)(int x, int y); //this code
} bstree;
c文件
void bst_init_with_comp_operator(bstree *bst, int(*comp)(int x, int y)) {
bst_init(bst);
bst->compare_keys = comp; // what does this mean? a fucntion pointer parameter to function pointer to struct?
}
//如果x应该被视为小于y,则comp应该返回-1;如果x应该在此处输入代码(等于y),则返回零;如果x应该被视为大于y,则返回1。
所以我创建了这个函数:
int compare (int x , int y)
{
if(x < y) return -1;
else if(x == y) return 0;
else return 1;
}
main.c
bstree tree;
bst_init_with_comp_operator(&tree,compare(2,3))
但它不起作用...
通常我们只需要这样的东西
int function(int x, int y)
{ return x+y;}
int (*pointerf) (int , int)
pointerf = function;
pointerf(2,3)
您只需要bst_init_with_comp_operator(&tree,compare))
,这将传递一个函数地址作为参数,而如果您进行compare(a,b)
则传递该函数的结果,因此整数1、0或-1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.