Hello everyone! I have a question regarding the structure definition below:
1 2 3
struct elem
{int inf;
elem *adr;}
The matter isn't the program but my logic is. I mean, when I declare adr as a normal variable (without asterisk) , I'm given the error that adr has an incomplete data type or sth like that, which I agree with because elem structure isn't actually terminated at adr declaration, but when I declare it as a pointer, it doesn't show any error. And this is what I don't understand. Why? Thanks in advance!
How big is one Foo? At least sizeof(int)+sizeof(Foo).
Oh, wait! The fubar contains an int and a Foo, which contains an int and a Foo, which contains an int and a Foo, which contains an int and a Foo, ....
Incomplete definition and infinite recursion.
1 2 3 4
struct Bar {
int inf;
Bar* bar;
};
How big is one Foo? At least sizeof(int)+sizeof(Bar*).
How big is Bar*? The Bar* is a pointer type, so it is large enough to store a memory address.
Totally independent of the actual type Bar.
When declaring a pointer you don't need the full struct definition. It's enough that the compiler knows that elem is a struct.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Declares a struct named elem. This will allow you to create pointers
// to elem. It will also allow you to declare (but not define) functions
// with parameters of type elem.
struct elem;
// Pointer to object of type elem.
elem* ptr;
// Defines the struct named elem. This will allow you to create objects
// of type elem.
struct elem { int inf; elem *adr; };
// Object of type elem.
elem obj;