3

I am relatively new to C++ and am having problems understanding struct.

I have a struct declared as follow

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

However the code fails to compile and reports error C2148: total size of array must not exceed 0x7fffffff bytes.

But the following code compiles

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

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

Thanks!

1
  • What compiler? As someone else pointed out, it could give you better diagnostics in this case. Commented Oct 18, 2009 at 23:19

4 Answers 4

5

This fails to compile, because the compiler needs to know the size of each type. So, what's sizeof(MyNode) ? It's sizeof(int) * 2 + sizeof(MyNode) : The recursion makes the size impossible to figure out.

You need a pointer, as in your second example. Why does this works ? Because sizeof(MyNode*) is known : it's the size of an address on the target platform.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks TheSamFrom1984! I finally understand what's going on with your given example and got my code to work. :D
1

The problem with the first example is that you have a recursive expansion of your structure. Every child MyNode contains four MyNodes itself which in turn contain another four MyNodes which in turn... You get the picture.

You'll need to use a single pointer per child to indicate the depth of the tree.

Comments

1

Have a look at this. You need to get to understand "Forward References".

Comments

0

You can't construct a struct that uses its own type as the type of one of its fields, because at run time the compiler wouldn't know what size the total structure would be. How you're writing the struct is exactly how it would look in memory, ie 4 bytes for level, 4 bytes for index and ?? bytes for MyNode. See the problem?

Now in the 2nd example, you know the type of MyNode::children, it's a pointer, so its size is 4 (on a 32 bit windows system), so the total size of the struct is known: 4+4+4=12.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.