2010-01-29 146 views
4

我一直在試圖弄清楚今天大部分時間裏的指針,甚至在早些時候問過一個question,但現在我被困在別的東西上了。我有下面的代碼:在一個新的文件從不兼容的指針類型警告傳遞參數

typedef struct listnode *Node; 
typedef struct listnode { 
    void *data; 
    Node next; 
    Node previous; 
} Listnode; 

typedef struct listhead *LIST; 
typedef struct listhead { 
    int size; 
    Node first; 
    Node last; 
    Node current; 
} Listhead; 

#define MAXLISTS 50 

static Listhead headpool[MAXLISTS]; 
static Listhead *headpoolp = headpool; 

#define MAXNODES 1000 

static Listnode nodepool[MAXNODES]; 
static Listnode *nodepoolp = nodepool; 

LIST *ListCreate() 
{ 
    if(headpool + MAXLISTS - headpoolp >= 1) 
    { 
     headpoolp->size = 0; 
     headpoolp->first = NULL; 
     headpoolp->last = NULL; 
     headpoolp->current = NULL; 
     headpoolp++; 
     return &headpoolp-1; /* reference to old pointer */ 

    }else 
     return NULL; 
} 

int ListCount(LIST list) 
{ 
    return list->size; 

} 

現在我有:

#include <stdio.h> 
#include "the above file" 

main() 
{ 
    /* Make a new LIST */ 
    LIST *newlist; 
    newlist = ListCreate(); 
    int i = ListCount(newlist); 
    printf("%d\n", i); 
} 

當我編譯,我得到以下警告(在printf語句打印什麼應該):

file.c:9: warning: passing argument 1 of ‘ListCount’ from incompatible pointer type 

我應該擔心這個警告嗎?代碼似乎做我想做的事情,但我顯然非常困惑於C中的指針。在瀏覽本網站上的問題後,我發現如果我向ListCount (void *) newlist發送參數,我不會收到警告,我不明白爲什麼,也沒有什麼(void *)真的...

任何幫助,將不勝感激,謝謝。

+0

ListCount接受LIST?什麼是LIST?它在哪裏定義?你通過它LIST * – 2010-01-29 07:08:42

+0

如果你沒有'typedef'指針類型,代碼將更容易被讀/調試。 – 2010-01-29 07:10:17

+0

根據我的理解,LIST是一個指向名爲Listhead的結構體的指針。我對嗎? – hora 2010-01-29 07:11:55

回答

5

由於多個typedefs,你會感到困惑。 LIST是表示指向struct listhead的指針的類型。所以,你希望你的ListCreate函數返回一個LIST,不是LIST *:以上

LIST ListCreate(void) 

說:ListCreate()功能,如果它可以返回一個指針到一個新的列表的頭。

然後,您需要將函數定義中的return語句從return &headpoolp-1;更改爲return headpoolp-1;。這是因爲你想返回最後一個可用的頭指針,而你剛增加了headpoolp。所以現在你想從它減去1並返回。

最後,您main()需要被更新,以反映上述變化:

int main(void) 
{ 
    /* Make a new LIST */ 
    LIST newlist; /* a pointer */ 
    newlist = ListCreate(); 
    int i = ListCount(newlist); 
    printf("%d\n", i); 
    return 0; 
} 
+0

Ohhhh哇,好吧,我明白髮生了什麼事。上面的@ unwind的評論幫助我理解了我在使用typedef時所做的事情。所以我認爲我讓LIST指向了typedef中的結構體,然後當我嘗試創建一個指針時,事情並不快樂。我改變了這種方式,所以現在我很確定我最終得到了與您的建議相同的結果,只是以較不混亂的方式編寫而已。謝謝! – hora 2010-01-29 07:35:05

+0

此警告是否可以強制報告爲錯誤? – Danijel 2016-12-02 13:14:16

相關問題