2014-10-30 181 views
0

您好我一直在尋找stackoverflow,我真的在掙扎函數指針作爲參數。函數指針作爲參數在C

我具有以下結構:

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; 
} 

注:該功能在前面加上包含了結構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 *)給出。

回答

2

在您的來電selectionsort你其實調用這些函數指針,從而導致您通過這些的結果致電selectionsort。它們是正常變量,應該像任何其他變量參數一樣傳遞給selectionsort

但是,你實際上並不需要的變量,你可以直接傳遞功能:

selectionsort(&compare, &swap, argc); 

需要注意的是運營商,地址並不是必需的,但我更喜歡明確地使用它們告訴讀者,我們通過指針這些功能。

3

selectionsort(compareData(list, list->next), swapData(list, list->next), argc); 

您傳遞調用該​​函數compareData的結果。這是錯誤的。

這同樣適用於swapData

(指針RESP它。)只是傳遞函數本身:

selectionsort(compareData, swapData, argc); 
+3

swapData ... – 2014-10-30 08:35:43

+1

@Andreas Compoletely正確的,我錯過了... – glglgl 2014-10-30 08:37:00

+0

謝謝!我覺得沒有發現有點傻,但無論你的及時答覆是非常感激。 – thyde 2014-10-30 08:40:49