Reputation: 201
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). But I can't, it occurs some errors(One is error: unknown type name 'Bar'
) in the compile time.
How to do it?
Upvotes: 8
Views: 9235
Reputation: 6717
The compiler needs to be able to determine the size of Foo
. If Bar
is unknown at the time Foo
is defined the compiler can not determine the size of 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
. 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();
}
Upvotes: 16
Reputation: 2995
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)
Upvotes: -2
Reputation: 11
The Bar struct declaration has to precede the Foo struct declaration - in case you do not want to use pointers and allocate memory. 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.
Upvotes: 1