[英]C Declare the struct before definition
The following is the source code that is problem: 以下是问题的源代码:
#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;
}
I want to declare the Bar
struct in the Foo
struct that keep order of the struct declarations ( Foo
struct is first). 我想声明Foo
结构中的Bar
结构,它保持结构声明的顺序( Foo
结构是第一个)。 But I can't, it occurs some errors(One is error: unknown type name 'Bar'
) in the compile time. 但我不能,它在编译时发生了一些错误(一个是error: unknown type name 'Bar'
)。
How to do it? 怎么做?
The compiler needs to be able to determine the size of Foo
. 编译器需要能够确定Foo
的大小。 If Bar
is unknown at the time Foo
is defined the compiler can not determine the size of Foo
. 如果在定义Foo
未知Bar
则编译器无法确定Foo
的大小。 The only way around this is using a pointer since all pointers have the same size. 唯一的解决方法是使用指针,因为所有指针都具有相同的大小。
You can use a forward declaration of the structure and then reference it as a pointer. 您可以使用结构的前向声明,然后将其作为指针引用。 This means that Foo
can never automatically allocate the memory for Bar
. 这意味着Foo
永远不会自动为Bar
分配内存。 As a consequence the memory has to be allocated separately. 因此,必须单独分配内存。
If you can avoid this do not do it. 如果你能避免这种情况就不要这样做。
#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();
}
The Bar struct declaration has to precede the Foo struct declaration - in case you do not want to use pointers and allocate memory. Bar结构声明必须在Foo结构声明之前 - 如果您不想使用指针并分配内存。 In C, if you have another struct as a member in a struct, the other struct has to be declared before so as the compiler can see it. 在C中,如果在结构中有另一个结构作为成员,则必须先声明另一个结构,以便编译器可以看到它。
Tada! 田田!
#define Bar struct { int a; int b; }
typedef struct Foo
{
int a;
Bar b;
} Foo;
#undef Bar
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;
}
(please don't do this) (请不要这样做)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.