【问题标题】:How do I define and typedef a struct containing a pointer to itself? [closed]如何定义和 typedef 包含指向自身的指针的结构? [关闭]
【发布时间】:2016-08-02 02:37:36
【问题描述】:

我有两个文件(每个文件都有 .h 和 .c)。我在其中一个头文件中定义了以下结构:

 typedef struct Client{
    int fd;
    struct in_addr ipaddr;
    struct Player * p;
    struct Client * next;
 }Client;

我尝试了许多不同的 typedef 和 struct 建议组合,但我仍然收到error: redefinition of ‘struct client’

我开始认为这与两个头文件相互包含的事实有关。

我是否正确地创建了这个结构?在相互包含头文件时,我应该遵循一些基本规则吗?

【问题讨论】:

  • 我认为您的问题与包含指向自身的指针的结构无关。
  • 这个问题的问题是你发布的代码不会产生那个错误。需要minimal, complete, and verifiable example
  • 我最好的猜测是你要找的是header guards
  • 您向我们展示的代码is correct。因此,问题出在您没有向我们展示的代码中。请将您的程序缩减为实际显示错误的最小完整程序。请参阅minimal reproducible example 了解更多信息。

标签: c struct typedef


【解决方案1】:

如果你有两个相互依赖的结构,你可以转发声明其中一个。

typedef struct Client Client;   // forward declaration of struct Client

typedef struct Player {
    ...
    Client *client;
    ...
} Player;

struct Client{
    int fd;
    struct in_addr ipaddr;
    Player * p;
    Client * next;
};

【讨论】:

    【解决方案2】:

    typedef struct x3 { ... } x3;

    标签和 typedef 使用相同的名称是合法的,因为它们存在于不同的命名空间中。

    http://c-faq.com/struct/typedef.html

    【讨论】:

      猜你喜欢
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多