nested structs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int fn() {return 5;}

struct outer
{
    int (*FnPtrA)();
    struct middle
    {
        struct inner
        {
            int (*FnPtrB)();
            int k;
        };
    };
};


int _tmain(int argc, _TCHAR* argv[])
{
    outer obj = {0};//sets the only 4 bytes in obj to zero
    size_t i = sizeof(obj);// = 4 <--- why not 12?
    size_t ii = sizeof(outer);// = 4 <--- why not 12?
    size_t iii = sizeof(outer::middle);// = 1 <--- why not 8?
    size_t iv = sizeof(outer::middle::inner);// = 8

    obj.FnPtrA = fn;//writes to only 4 bytes in obj
    obj.middle::inner::FnPtrB = fn;//writes to same mem as obj.FnPtrA = fn

    return 0;
}


I can't understand why the size of outer isn't 12. I want to create a nested set of structs like this with function pointers in them, but the number of bytes created by outer obj is only 4?

(c++, 32 bit machine)
Last edited on
You're only declaring structs within the inner scopes.

You're not declaring member instances of your inner structs.

1
2
3
4
5
6
7
8
9
10
11
12
13
struct outer
{
    int (*FnPtrA)();
    struct middle
    {
        struct inner
        {
            int (*FnPtrB)();
            int k;
        };
    };
    middle oojamaflip;  // now you'll see a change in size.
};

throwing style out the window here, the answer is that you define structs but don't have any INSTANCES of them. Once you have instances of them, the size changes :)

try it like this:

1
2
3
4
5
6
7
8
9
10
11
12
struct outer
{
    int (*FnPtrA)();
    struct middle
    {
        struct inner
        {
            int (*FnPtrB)();
            int k;
        }moo;
    }derp;
};


gives 12,12,8,8 for 1,2,3,4

personally I feel that nested structs are not a good idea. They bring nothing to the table; if you just had them independent you could has-a them together AND reuse them AND keep the syntax a little cleaner.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
struct outer
{
    int (*FnPtrA)();
    struct middle
    {
        struct inner
        {
            int (*FnPtrB)();
            int k;
        } inn;
    } mid;
};


Thank you. That was driving me nuts. Apparently I also need to do

 
obj.mid.inn.FnPtrB = fn;


and not

 
obj.middle::inner::FnPtrB = fn;


which always did look odd to me...
Thank you. That was driving me nuts. Apparently I also need to do

obj.mid.inn.FnPtrB = fn;

and not

obj.middle::inner::FnPtrB = fn;


Indeed. Remember, outer::middle and outer::middle::inner are not variables that can have values assigned to them. They are simply types.
Topic archived. No new replies allowed.