Could someone please explain to me whats wrong with this code?
#include<stdio.h>
struct A{
int i;
struct A* parent;
struct B test; // error: field ‘test’ has incomplete type
};
struct B{
struct A* rootParent;
int ref;
int something;
};
int main(){
struct A some, some2;
some.i = 0;
some.parent = &some2;
some.test.rootParent = &some;
some.test.ref = some.test.something = 0;
some2.i =0;
some2.parent = 0;
some2.test.rootParent = 0;
some2.test.ref = some2.test.something = 0;
return 0;
}
It seems I’m missing something basic here. Why does the order of A and B matter?
Is it possible to make it so it will not matter?
If I change the order of deceleration everything works, B first.
cnicutar is almost right. Here’s an explanation and the correct answer which is to reorder the declarations.
The compiler needs to calculate the size of a
structwhen it reads the definition. In your case, the size ofstruct Bis unknown so you are getting an error. So you can swap the order of declaration in this simple case:Which will work even though
struct Ais an unknown type. It only works because the reference to the type is a pointer so the size is known. If you think that you need two types that contain full instances of each other, then you cannot use this method. In fact, you cannot declare astruct Athat contains astruct Bby-value which contains astruct Amember by-value. It turns out that it is rather non-sensical anyway – one of the links is required to be a reference.