2014-03-19 20 views
4

我在閱讀算法設計手冊,並在第3章中出現了以下代碼片段。它與刪除鏈接列表中的項目有關。這個問題與數據結構無關,但只是一行代碼中聲明瞭兩個變量我認爲。爲了簡潔起見,我已經將代碼中不相關的部分分開了。算法設計手冊第3章鏈表代碼片段混淆

list *search_list(list *l, item_type x) { 
    // This function just searches the list x 
} 

list *predecessor_list(list *l, item_type x) { 
    // This function simply returns the predecessor of x or NULL 
} 

delete_list(list **l, item_type x) { 
    list *p;  /* item pointer */ 
    list *pred; /* predecessor pointer */ 

    list *search_list(), *predecessor_list(); // What are these declarations? 

    p = search_list(*l,x); 

    // Code to delete the node if found is here  
} 

我的問題是在delete_list function,具體而言,線路list *search_list(), *predecessor_list();。那條線上發生了什麼?我猜這是一個指向函數的指針,但我的理解是你應該用合適的參數聲明函數指針。另外,假設我是正確的,爲什麼這些線路甚至需要?

+0

我想這些都是函數聲明,(沒有原型聲明)。在這裏閱讀http://stackoverflow.com/a/5481685/2549281,我很確定他們不是必需的。嘗試刪除它們。 – Dabo

+0

代碼可以正常工作,但是,乍一看,這很奇怪。我讀它爲「search_list是指向返回列表的函數的指針」,這顯然沒有意義。 – logbaseinfinity

+1

你的大部分問題都已經得到解答,所以我只對你說的部分發表評論:「我猜這是一個指向函數的指針」。爲了將來的參考 - 指向函數的指針需要圍繞'*'和函數名稱:'list(* search_list)()'的括號。 – ruakh

回答

3

有問題的線路,

list *search_list(), *predecessor_list(); 

通知了function一個identifier存在編譯器以及它的返回類型。在這種情況下,函數所需的參數的數量和類型不是必需的。

我同意這有點奇特,不是很直觀,但是,C語言支持許多這樣的特性。

通過達博在評論提供給你的問題的鏈接進入更多細節:Why does an empty declaration work for definitions with int arguments but not for float arguments?

2

這些都是函數聲明,以告知search_list()predecessor_list()回報list*。如果你在聲明它之前使用了一個函數,它將被隱式聲明爲「函數返回int」。在功能search_list()predecessor_list()delete_list之前定義的情況下,您將不需要這些聲明。

試圖把這些功能delete_list後刪除聲明,你會得到conflicting types for search_list()爲你的編譯器將假定search_list()predecessor_list()應該返回int