C在定义之前声明结构

Lee*_*Gom 5 c struct

以下是问题的源代码:

#include <stdio.h>

typedef struct Foo
{
    int a;
    Bar b;
} Foo;

typedef struct Bar
{
    int a;
    int b;
} Bar;

int main(void)
{
    Foo f;
    f.a = 1;
    f.b.a = 2;
    f.b.b = 3;
    printf("%d %d %d\n", f.a, f.b.a, f.b.b);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想在Bar结构中声明结构,该Foo结构保持结构声明的顺序(Foo结构是第一个).但我不能,它error: unknown type name 'Bar'在编译时发生了一些错误(一个是).

怎么做?

Joh*_*nes 10

编译器需要能够确定Foo的大小.如果在定义Foo时未知Bar,则编译器无法确定Foo的大小.唯一的解决方法是使用指针,因为所有指针都具有相同的大小.

您可以使用结构的前向声明,然后将其作为指针引用.这意味着Foo永远不会自动为Bar分配内存.因此,必须单独分配内存.

如果你能避免这种情况就不要这样做.

#include <stdio.h>
#include <stdlib.h>

typedef struct Bar Bar;
typedef struct Foo Foo;

struct Foo
{
    int a;
    Bar * b;
};

struct Bar
{
    int a;
    int b;
};

void dynamic(void)
{
    Foo f;

    f.a = 1;
    f.b = (Bar*)malloc(sizeof(Bar));
    f.b->a = 2;
    f.b->b = 3;
    printf("%d %d %d\n", f.a, f.b->a, f.b->b);

    free(f.b);
}

void automatic(void)
{
    Foo f;
    Bar b;

    f.a = 1;
    f.b = &b;
    f.b->a = 2;
    f.b->b = 3;
    printf("%d %d %d\n", f.a, f.b->a, f.b->b);
}

int main(void)
{
    dynamic();
    automatic();
}
Run Code Online (Sandbox Code Playgroud)