tags:

views:

185

answers:

5

Hi!

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!

+5  A: 

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)... Recursivity, size is mathematically infinite...

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

Samuel_xL
Thanks TheSamFrom1984!I finally understand what's going on with your given example and got my code to work. :D
gsf
you got a stupid compiler. GNU C/++ gives clear errors.
EffoStaff Effo
A: 

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.

Blindy
+1  A: 

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.

Timo Geusch
+1  A: 

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

jldupont
A: 

Hi guys!

Thanks for your help, I finally understand what's going on and got my code to work.

Cheers!

:D

gsf