c - C中的交叉引用结构

标签 c pointers struct reference

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

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

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

最佳答案

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

关于c - C中的交叉引用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20341335/

相关文章:

在 malloc() 的 char 指针上调用 free() 会导致程序因指针无效而崩溃

c - 如何在 c 中将链表中的所有字符串大写?

c++ - C++中一个简单的链表实现

c - 多次分配后C指针丢失

c - C中的链表/指针

c - 为结构的指针内部的双指针结构动态分配内存的改进

在 C 中创建没有依赖关系的 gotoxy() 函数

html - 如何避免在C中使用系统命令打印'echo'输出

c++ - 将光标位置存储在类对象中(ncurses c++)

C: 运算符 -> 和 *