【问题标题】:Cross referencing structs in CC中的交叉引用结构
【发布时间】:2013-12-03 01:46:58
【问题描述】:

有没有办法创建两个相互引用的结构? 示例:

struct str1
{
  struct str1* ptr1;
  struct str2* ptr2;
}

struct str2
{
  struct str1* ptr1;
  struct str2* ptr2;
}

【问题讨论】:

  • jsut 添加前向引用:将struct str2; 放在顶部。
  • 从变量的角度考虑结构和函数可能会有所帮助。结构只是一个包含更多变量的变量,而函数只是一个可以作用于自身的变量。考虑到这一点,您只需在使用前声明要使用的内容,即使您尚未定义它,就像任何其他变量一样,您会没事的。
  • 是的,错了,我的错

标签: c pointers struct reference


【解决方案1】:
struct str2; // put a forward reference to str2 here

struct str1
{
  struct str1* s1;
  struct str2* s2;
};

struct str2
{
  struct str1* s1;
  struct str2* s2;
};

int main()
{
  struct str1 s1;
  struct str2 s2;

  s1.s1 = &s1;
  s1.s2 = &s2;
  s2.s1 = &s1;
  s2.s2 = &s2;

  return 0;
}

【讨论】:

    【解决方案2】:
    typedef struct str1 str1_t;
    typedef struct str2 str2_t;
    struct str1
    {
      str2_t *user1;
      str2_t *user2;
    }
    
    struct str2
    {
       str1_t *user1;
       str1_t *user2;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      相关资源
      最近更新 更多