C – 取消引用指向不完整类型的指针

我已经阅读了关于同一错误的5个不同的问题,但我仍然无法找到我的代码有什么问题。

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; 

谢谢!

您不能这样做,因为结构是在不同的源文件中定义的。 typedef的重点是隐藏您的数据。 可能会调用graph_capgraph_size等函数来为您返回数据。

如果这是您的代码,您应该在头文件中定义struct graph ,以便包含此头文件的所有文件都能够定义它。

当编译器正在编译main.c它需要能够看到 struct graph的定义,以便它知道存在一个名为cap的成员。 您需要将结构的定义从.c文件移动到.h文件。

如果您需要graph_t为不透明数据类型 ,则另一种方法是创建访问器函数,该函数采用graph_t指针并返回字段值。 例如,

graph.h

 int get_cap( graph_t *g ); 

graph.c

 int get_cap( graph_t *g ) { return g->cap; } 

必须是您定义事物的顺序。 typedef行需要显示在包含main()的文件所包含的头文件中。

否则它对我来说很好。

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