简体   繁体   English

指向结构函数指针的函数指针

[英]Function pointer to a struct function pointer

Today I received a homework, about function pointer(binary tree) . 今天,我收到了有关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 ) 有一大堆我不明白的代码...我了解一个function pointer是什么以及它如何工作,但是大约有两个function pointersparameter中有1个)

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 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?

 }

// 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. //如果x应该被视为小于y,则comp应该返回-1;如果x应该在此处输入代码(等于y),则返回零;如果x应该被视为大于y,则返回1。

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 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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM