Cross referencing structs in C

2019-09-07 17:21发布

问题:

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;
}

回答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;
}