【问题标题】:Field has an Incomplete type?字段有一个不完整的类型?
【发布时间】:2013-12-07 18:07:29
【问题描述】:

我收到一个关于结构元素的错误。

struct trie {
        char ch;
        bool isEnd;
        struct trie arr[4];
        struct trie *next;
};

错误:

error: field ‘arr’ has incomplete type

【问题讨论】:

  • 你必须转发声明trie。否则当它试图在结构中使用自己时它的类型不完整
  • @amdixon 不会解决问题。 struct 不能包含自己。
  • 所以你的 trie 包含四个尝试,每个尝试包含四个尝试,每个尝试包含四个尝试,....

标签: c


【解决方案1】:

你可以这样定义你的结构

struct trie {
    char ch;
    bool isEnd;
    struct trie *arr[4];
    struct trie *next;
};

请注意(为了避免无限递归)arr 现在是一个由四个 指针 组成的数组,每个指针都指向一个您必须动态分配的 trie 结构在你的代码上。

你可以用这个函数分配一个trie(当然是未初始化的):

struct trie *alloc_trie() {
    return malloc(sizeof(struct trie));
}

注意arr的四项所指向的四个trie没有分配。 下一个也不是。

【讨论】:

    【解决方案2】:

    你不能把一个结构放在自己身上(想想吧,它没有意义)。它会导致关于类型的“无限递归”。也许您可以使用另一个指向struct trie 的指针,您可以为其动态分配内存。但我不确定你想要达到什么目的。也许你想要一个指针数组? struct trie *arr[4] 或类似的。

    【讨论】:

      【解决方案3】:

      转发声明如下:

      typedef struct trie trie;
      
      struct trie {
        char ch; 
        int isEnd; //bool unsupported for c89 so..
        trie *arr; //have to manually alloc 4 trie here..
        trie *next;
      };
      

      编辑:从命名中删除了下划线,如 c99 草案标准的 7.1.3 Reserved Identifiers 部分所示[以 cmets 表示]

      【讨论】:

      • 前向声明不是问题。问题是数组(您已在答案中删除)。
      • 无需转发声明。 struct _trie * next 可以胜任。
      • _ 开头的全局范围内的标识符(或struct 标签)是“否”。只需对两者都使用trie 就可以了。
      • @JensGustedt 认为这取决于偏好。但是使用 _ 前缀命名结构通常是在这种使用 nicer 名称键入def 的上下文中完成的。
      • @amdixon 不,这不是“偏好”。全局名称前加下划线是为实现保留的;任何这样做的用户代码都有未定义的行为。
      猜你喜欢
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多