Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Misunderstanding of the structure С++ [closed]

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 ?

like image 603
Optimus1 Avatar asked Jan 24 '23 04:01

Optimus1


2 Answers

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.

like image 118
Vlad from Moscow Avatar answered Jan 30 '23 06:01

Vlad from Moscow


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.

like image 38
hyde Avatar answered Jan 30 '23 04:01

hyde