Can I create an instance of one structure in its own structure (recursive structure) in C (although I do of course now that this is kind of bizarre and tricky)?
Like:
int main(void)
{
struct type
{
char name[20];
char address[35];
struct type;
};
return 0;
}
Of course, the compiler gives me the warning:
warning: declaration does not declare anything
but he/it let it pass and gives me an executable program though.
As I´d wanted to compile the same program with a C++ compiler, he/it threw an error:
error: ‘main()::type::type’ has the same name as the class in which it is declared
So the question is for C, not for C++.
Thanks in advance.
To begin with, struct type;
is a forward declaration, not a member variable definition. Secondly, no you can't do it, you need to use pointers.
To use a structure it must be fully defined, the definition have to end (with the closing }
) before it can be used. Otherwise the compiler doesn't know the full size of the structure and don't know how big it is and how must memory to reserve for instances of the structure.
But to create a pointer to a structure, all the compiler needs to know is the structure tag (type
in your case). That's because the size of a pointer is know at compile-time. The size of the full structure itself doesn't need to be known at that point.