c - C 操作方法和用例中结构的前向声明

标签 c

我正在研究 struct,并且在网络上的某处我看到了“循环 struct”的示例。我有三个问题(基于下面的代码):

struct A {
    struct B* b; //does not work if it is not a pointer
    int data;
};

struct B {
    struct A* a; //does not work if it is not a pointer
    int data;
};

int main(void)
{
    struct A sA;
    struct B sB;

    sA.b = &sB;
    sB.a = &sA;

    sA.b->data = 1;
    sB.a->data = 2;

    printf("a = %d, b = %d", sA.b->data, sB.a->data);
}

1) 为什么struct 成员是一个指针?如果不是指针,则无法编译。

2) 我是否正确地声明和使用了struct

3) 我不知道这种习语的潜在用例是什么。能举几个例子吗?

最佳答案

why the inner-struct should be a pointer, with out the pointer it does not compile.

编译器需要知道您的数据类型的大小,并根据其成员的大小计算出这一点。它知道指向 struct 的指针的大小。将是,即使它没有看到 struct yet, 但它不知道 struct 的大小本身。

Did I declared, and used the structs correctly?

乍一看还不错。你编译了吗?您的代码是否按预期运行?

I have no idea what can be a potential use-case for such idiom. Can you give me some examples?

链表是最简单和最常见的示例(struct 包含指向相同类型的 struct 的指针)。

关于c - C 操作方法和用例中结构的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49468257/

相关文章:

c - 在 C 中使用 mmap 读取二进制文件时出现段错误

c - 函数的 undefined reference 错误

c++ - 编写驱动程序时解决方案资源管理器中没有文件

c - 递增运算符在 if 语句中如何工作?

c - C语言中外部变量的使用

c - 当我传入一个非零值作为参数时,为什么这个函数打印 0?

c - Knowledge Flow 的 Obtain 24/7 产品使用哪个数据库引擎?

c++ - 将资源文件嵌入可执行文件的性能

c - 65535和65535UL有什么区别

c - 如何将 4 个字节/整数保存为 Short?