2012-03-07 68 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; } 
相关问题