![](/img/trans.png)
[英]Trying to declare an array of struct room inside of the room struct definition in C
[英]C Declare the struct before definition
以下是問題的源代碼:
#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;
}
我想聲明Foo
結構中的Bar
結構,它保持結構聲明的順序( Foo
結構是第一個)。 但我不能,它在編譯時發生了一些錯誤(一個是error: unknown type name 'Bar'
)。
怎么做?
編譯器需要能夠確定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();
}
Bar結構聲明必須在Foo結構聲明之前 - 如果您不想使用指針並分配內存。 在C中,如果在結構中有另一個結構作為成員,則必須先聲明另一個結構,以便編譯器可以看到它。
田田!
#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;
}
(請不要這樣做)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.