Cross referencing structs in C

[亡魂溺海] 提交于 2020-01-17 04:37:11

问题


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


来源:https://stackoverflow.com/questions/20341335/cross-referencing-structs-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!