2012-03-07 65 views
1

我已經閱讀了關於同一個錯誤的5個不同的問題,但我仍然無法找到與我的代碼有什麼問題。C - 取消引用指向不完整類型的指針

的main.c

int main(int argc, char** argv) { 
    //graph_t * g = graph_create(128); //I commented this line out to make sure graph_create was not causing this. 
    graph_t * g; 
    g->cap; //This line gives that error. 
    return 1; 
} 

.C

struct graph { 
    int cap; 
    int size; 
}; 

.H

typedef struct graph graph_t; 

謝謝!

+0

請告訴我的錯誤? – 2012-03-07 17:42:40

+0

@GregBrown:他正在取消引用指向不完整類型錯誤的指針。 – 2012-03-07 17:43:37

回答

2

由於struct是在不同的源文件中定義的,所以你不能這麼做。 typedef的要點是隱藏你的數據。可能存在諸如graph_capgraph_size之類的函數,您可以調用該函數以返回數據。

如果這是你的代碼,你應該在頭文件中定義struct graph,這樣所有包含這個頭文件的文件都能夠定義它。

+0

謝謝,這很有道理。還要感謝其他同樣回答我的問題的人。 – user1255321 2012-03-07 17:51:54

0

必須是您定義事物的順序。 typedef行需要顯示在包含main()的文件的頭文件中。

否則它對我來說工作得很好。

0

lala.c

#include "lala.h" 

int main(int argc, char** argv) { 
    //graph_t * g = graph_create(128); //I commented this line out to make sure graph_create was not causing this. 
    graph_t * g; 
    g->cap; //This line gives that error. 
    return 1; 
} 

lala.h

#ifndef LALA_H 
#define LALA_H 

struct graph { 
    int cap; 
    int size; 
}; 

typedef struct graph graph_t; 

#endif 

這編譯沒有有問題的:

gcc -Wall lala.c -o lala 
1

當編譯器在編譯main.c它需要能夠看到定義struct graph,以便知道存在名爲cap的成員。您需要將結構的定義從.c文件移動到.h文件。

如果您需要graph_topaque data type,則另一種方法是創建存取函數,該函數採用graph_t指針並返回字段值。例如,

graph.h

int get_cap(graph_t *g); 

graph.c

int get_cap(graph_t *g) { return g->cap; } 
相關問題