簡體   English   中英

指向結構函數指針的函數指針

[英]Function pointer to a struct function pointer

今天,我收到了有關function pointer(binary tree) 有一大堆我不明白的代碼...我了解一個function pointer是什么以及它如何工作,但是大約有兩個function pointersparameter中有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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM