Some questions about C ++ structure and array

I am relatively new to C ++ and I have problems understanding the structure.

I have a structure declared as

struct MyNode {
    int level;
    int index;
    MyNode children[4];
}

However, the code does not compile and reports error C2148: the total size of the array should not exceed bytes 0x7fffffff.

But the following code compiles

struct MyNode {
    int level;
    int index;
    MyNode* children;
}

Can I encode MyNode, as in the first example, or is there something that I am missing.

Thanks!

+3
source share
4 answers

This does not compile, because the compiler must know the size of each type. So what sizeof(MyNode)? This sizeof(int) * 2 + sizeof(MyNode): recursion makes sizing impossible.

, . ? sizeof(MyNode*) : .

+5

, . MyNode MyNodes, , , MyNodes, ... .

.

+1

. " ".

+1

You cannot build a structure that uses its own type as the type of one of its fields, because at runtime the compiler does not know what size the general structure will have. How do you write a structure exactly as it will look in memory, i.e. 4 bytes for a level, 4 bytes for an index and? bytes for MyNode. See the problem?

Now in the second example, you know the type MyNode :: children, this is a pointer, therefore its size is 4 (on a 32-bit Windows system), therefore the total size of the structure is known: 4 + 4 + 4 = 12.

0
source

Source: https://habr.com/ru/post/1720389/


All Articles