Today I received a homework, about function pointer(binary tree)
. There is a chunk of code that i can not understand... I understand what a function pointer
is and how it work but what about 2 function pointers
(1 is in a parameter
)
header.h
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 file
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?
}
// comp is supposed to return -1 if x should be treated as less than y,zero if x should enter code here` be treated as equal to y, or 1 if x should be treated as greater than y.
so I created this function:
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))
but it doesnt work ...
normally we just need something like this
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。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.