C-取消对不完整类型的引用指针

C-取消对不完整类型的引用指针,c,compiler-errors,C,Compiler Errors,我已经阅读了关于同一个错误的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

我已经阅读了关于同一个错误的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

h


谢谢

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


否则,它对我来说效果很好。

您不能这样做,因为结构是在不同的源文件中定义的。typedef的全部目的是对您隐藏数据。您可能可以调用
graph\u cap
graph\u size
等函数来为您返回数据

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

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

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

如果需要将
graph\t
作为一个函数,另一种方法是创建访问器函数,该函数使用
graph\t
指针并返回字段值。比如说,

图h

int get_cap( graph_t *g );
图c

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

@GregBrown:他得到了指向不完整类型错误的解引用指针。谢谢,这很有意义。也感谢其他人也回答了我的问题。
int get_cap( graph_t *g );
int get_cap( graph_t *g ) { return g->cap; }