在C中交叉引用结构

时间:2013-12-03 01:46:59

标签: c pointers struct reference

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

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

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