【问题标题】:Multiple structs containing an instance of eachother包含彼此实例的多个结构
【发布时间】:2013-04-01 14:10:50
【问题描述】:

对于一个作业,我需要声明多个结构,这没有问题。这些声明如下:

typedef struct struct1{
  struct2* object;
}

typedef struct struct2{
  struct1* object;
}

// functions using both struct1 and struct2 parameters

当然,这会给我一个错误,因为 struct2 没有在 struct1 之前声明。因此,我尝试预先声明它,通过放置

struct struct2;

在顶部。但是,这需要我将 struct1 块中的对象称为

typedef struct struct1{
  struct struct2* obj;
}

这个结构中的函数将在使用 struct1* 和 struct2* 参数时使用,并且会被这样测试(包括构造函数)。使用上面示例中的结构标记会给我带来无数错误。有谁知道如何解决这个问题?

【问题讨论】:

    标签: c struct


    【解决方案1】:
    typedef struct s2 struct2;
    
    typedef struct s1 {
      struct2* object;
    } struct1;
    
    struct s2 {
      struct1* object;
    };
    

    【讨论】:

    • 我用 gcc gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4) 尝试过,我收到以下错误 main.c:12:3: error: redefinition of typedef ‘struct2’ main.c:4:19: note: previous declaration of ‘struct2’ was here
    • @MohamedKALLEL:gcc 4.7.2 默认情况下没有对此发出警告,但您说得对。我已经更正了答案。
    • 非常感谢,你们太棒了。 +1
    猜你喜欢
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多