簡體   English   中英

結構中的函數指針

[英]function pointers in a struct

我試圖弄清楚函數指針。 我的代碼看起來像這樣我有一個file.h ,我有一個有2個成員的結構

typedef struct _node_ {
    char* string;
    int (*compare)(int a, int b);
} node

在同一個文件中,我有一個名為的函數的原型:

void init_with_function_pointer(node* list, int (*comp)(int x, int y));

然后在我的file.c ,我定義了函數:

void init_with_function_pointer(node* list, int (*comp)(int x, int y)){
    node_init(list);
    list->compare = comp;
}

在我的main.c

int main(){
    node tree;
    init_with_function_pointer(&tree, /* what should I pass here */)
}

我需要指出的那個函數應該在file.c定義

但我不能讓它工作,如果我在main中定義函數並傳遞它,那么它可以工作,但如果我嘗試使用extern用於我在file.c定義的相同函數,編譯器告訴我comp是沒有定義的。

這是我的功能,我想指出:

extern int comp(int x,int y) {
  if (x < y) {
    return -1;
  } else if(x == y) {
    return 0;
  } else {
    return 1;
  }
}

有人能幫我嗎?

你需要file.h comp函數的file.h

int comp(int, int);

然后在main()寫道:

init_with_function_pointer(&tree, comp);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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