Cross referencing structs in C

2019-09-07 17:12发布

Is there a way to create two structs that make a reference to each other? Example:

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

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

2条回答
仙女界的扛把子
2楼-- · 2019-09-07 17:53
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;
}
查看更多
姐就是有狂的资本
3楼-- · 2019-09-07 17:53
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;
}
查看更多
登录 后发表回答