【问题标题】:C - Dereferencing pointer to incomplete typeC - 取消引用指向不完整类型的指针
【发布时间】:2012-03-07 17:37:41
【问题描述】:

我已经阅读了大约 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;

谢谢!

【问题讨论】:

  • @GregBrown:他正在取消引用指向不完整类型错误的指针。

标签: c compiler-errors


【解决方案1】:

您不能这样做,因为该结构是在不同的源文件中定义的。 typedef 的全部意义在于对您隐藏数据。您可能可以调用诸如graph_capgraph_size 之类的函数来为您返回数据。

如果这是你的代码,你应该在头文件中定义struct graph,这样所有包含这个头文件的文件都可以有它的定义。

【讨论】:

  • 谢谢,这很有意义。还要感谢其他也回答了我的问题的人。
【解决方案2】:

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

如果您需要graph_t 成为opaque data type,另一种方法是创建获取graph_t 指针并返回字段值的访问器函数。例如,

图形.h

int get_cap( graph_t *g );

图形.c

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

【讨论】:

    【解决方案3】:

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

    否则它对我来说很好。

    【讨论】:

      【解决方案4】:

      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
      

      【讨论】:

        猜你喜欢
        • 2013-03-11
        • 1970-01-01
        • 2018-05-31
        • 2013-08-07
        • 2017-11-02
        相关资源
        最近更新 更多