Search code examples
c++pointerssizeofincomplete-type

Misunderstanding of the structure С++


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 ?


Solution

  • 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.