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?
If a struct is declared in a header file in C++, you must include the header file everywhere a struct is used and where struct member functions are defined.
If the struct definition is needed from multiple . c files then it should go in the header, otherwise it doesn't have to. @M.M It is only needed in one . c file.
If you define the structure inside main() , the scope is limited to main() only. Any other function cannot see that definition and hence, cannot make use of that structure definition.
The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ }; Here tag_name is optional in some contexts.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With