[英]Function pointer as parameter in C
嗨,我一直在研究stackoverflow,我真的很努力地將函數指針作為參數。
我有結構:
struct Node {
struct Node *next;
short len;
char data[6];
};
和功能:
void selectionsort(int (*compareData)(struct Node *, struct Node *), void (*swapData)(struct Node *, struct Node *), int n);
compare(struct Node *a, struct Node *b);
swap(struct Node *a, struct Node *b);
選擇排序僅用於調用比較和交換:
void selectionsort(int compare(struct Node *a, struct Node *b), void swap(struct Node *a, struct Node *b), int n){
int i;
for (i = 0; i < n; i++){
compare(a, b);
swap(a, b);
}
}
(上面的內容可能不正確,我還沒有真正去了解實際的selectionsort函數)。
當我在main中調用selectionsort時會出現問題。 我覺得這可行:
int main(int argc, char **argv){
int n;
struct Node *list = NULL;
for (n = 1; n < argc; n++)
list = prepend(list, argv[n]); //separate function not given here.
int (*compareData)(struct Node *, struct Node *) = compare; //not sure I needed to redeclare this
void (*swapData)(struct Node *, struct Node *) = swap;
selectionsort(compareData(list, list->next), swapData(list, list->next), argc);
//other stuff
return 0;
}
注意:函數prepend包含該結構的malloc,因此已進行了處理。
我遇到的問題是無論我如何處理函數聲明等,我總是會遇到以下錯誤:
warning: passing argument 1 of 'selectionsort' makes pointer from integer without a cast [enabled by default]
note: expected 'int (*)(struct Node *, struct Node *)' but argument is of type 'int'.
我們非常感謝您提供任何幫助解釋為什么我收到此錯誤消息以及如何解決此錯誤消息。
我知道該函數需要一個函數指針,但是我認為上面的代碼將允許進行compare
。 任何輸入將不勝感激,這也是一個分配(所以請幫助我避免作弊)和參數int(*compareData)(struct Node *, struct Node *) void (*swapData)(struct Node *, struct Node *)
被給予。
在
selectionsort(compareData(list, list->next), swapData(list, list->next), argc);
您正在傳遞調用函數compareData
的結果。 錯了
swapData
也是swapData
。
只需傳遞函數本身(即指向它的指針):
selectionsort(compareData, swapData, argc);
在對selectionsort
的調用中,實際上是在調用這些函數指針,從而使您將這些調用的結果傳遞給selectionsort
。 它們是普通變量,應像其他任何變量參數一樣傳遞給selectionsort
。
但是,您實際上並不需要變量,您可以直接傳遞函數:
selectionsort(&compare, &swap, argc);
請注意,並非嚴格需要address-of運算符,但我更喜歡使用它們來明確告知讀者我們正在傳遞指向這些函數的指針 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.