I apologize in advance for the question if it seems too "childish", but the question is:
Here is such a simple code:
#include <iostream>
struct my_struct
{
struct fictitious_name fn_struct;
};
int main()
{
}
It is not compiled because the fictitious_name structure is not defined.
But then if I rewrite it thus:
#include <iostream>
struct my_struct
{
struct fictitious_name* fn_struct;
};
int main()
{
}
Then everything is fine, the code is compiled, but the fictitious_name structure is still undefined. Why does a pointer to a non - existent structure work ?
This declaration
struct fictitious_name fn_struct;
introduces incomplete type struct fictitious_name
. That is the size of an object of this type is unknown. As a result the compiler does not know how much memory to reserve for the object fn_struct
.
In this declaration
struct fictitious_name* fn_struct;
there is also introduced incomplete type struct fictitious_name
. But the size of the object fn_struct
that has a pointer type is known. It is the size of a pointer. So the object fn_struct
is of a complete type.
Pointers are always complete types.
From the C Standard (6.2.5 Types, p. #20)
A pointer type is a complete object type.
struct my_struct
{
struct fictitious_name fn_struct;
};
Here the contents of the inner struct are put in the outer struct. If definition is not known, size is not known and space can't be reserved.
struct my_struct
{
struct fictitious_name* fn_struct;
};
Here pointer to inner struct is put into outer struct. Pointer to struct has known size, so it's no problem. If you try to access members of the inner struct or use sizeof
on it (needed by malloc
for example), then you need the definition. Until then, it's just a pointer and C does not need to know more.
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