【问题标题】:declare element in array that is the struct type在数组中声明结构类型的元素
【发布时间】:2022-01-16 05:48:46
【问题描述】:

我有这个结构:

typedef struct {
    int id;
    node_t * otherNodes;
} node_t;

我的节点中需要一个节点数组......

但在头文件中无法识别:它告诉我`未知类型名称'node_t'

我该如何解决这个问题?

谢谢

【问题讨论】:

  • 这能回答你的问题吗? self referential struct definition?
  • 我会尝试..但我需要一个其他节点的数组
  • 解决方法是给结构本身命名。然后,您可以根据需要转发声明类型别名。或者在声明成员时使用结构名称。
  • 你学会了如何使用struct 没有使用typedef吗?因为那可能会阻止这个问题。

标签: c struct declaration typedef undeclared-identifier


【解决方案1】:

在这个 typedef 声明中

typedef struct {
    int id;
    node_t * otherNodes;
} node_t;

结构定义中的名称node_t 是一个未声明的名称。所以编译器会报错。

你需要写例子

typedef struct node_t {
    int id;
    struct node_t * otherNodes;
} node_t;

或者你可以写

typedef struct node_t node_t;

struct node_t {
    int id;
    node_t * otherNodes;
};

甚至喜欢

struct node_t typedef node_t;

struct node_t {
    int id;
    node_t * otherNodes;
};

【讨论】:

    【解决方案2】:

    我从内核代码中引用了struct list_head 的定义: https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/include/linux/types.h?h=v5.10.84#n178

    所以我会这样写:

    struct node {
        int id;
        struct node * otherNodes;
    };
    
    typedef struct node node_t;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      相关资源
      最近更新 更多