Codesmith
Codesmith

Reputation: 6792

double-recursive structs

I was confused about how I would create two structs that reference each other. I couldn't find any question like it asked before.
So, I know that this will compile just fine:

    struct MyStruct {
        MyStruct* p;
    };

But, for instance,

    struct A {
        B* pBstruct;
    };
    struct B {
        A* pAstruct;
    };

This won't compile.

Upvotes: 3

Views: 1247

Answers (2)

Codesmith
Codesmith

Reputation: 6792

So, I know I asked it, but I figured it out and thought that answering it might help others.

Just like making recursive functions, structures must also be prototyped.
So, consider making recursive functions:

    int fnc_a();
    int fnc_b();

    int fnc_a()
    {
        fnc_b();
    }
    int fnc_b()
    {
        fnc_a();
    }

The first two lines identify as the prototypes for the functions so that they can be used before their actual definition/declaration is provided.
Now consider making two recursive structs again:

    struct A;
    struct B;
    struct A {
        B* pBstruct;
    };
    struct B {
        A* pAstruct;
    };

These first two lines declare the existence of the two structs so that they can be used before they are declared. (Don't bother commenting on the fact I only need the B struct prototype - I do recognize that)

One final note, don't forget to use struct 'pointer' variables and not struct variables. This will not compile because it would create an infinitely large structure:

    struct A;
    struct B;
    struct A {
        B pBstruct;
    };
    struct B {
        A pAstruct;
    };

Upvotes: 2

Daniel Fischer
Daniel Fischer

Reputation: 183978

You need a forward declaration to make the type known:

struct B;
struct A {
    B* pBstruct;
};
struct B {
    A* pAstruct;
};

Upvotes: 6

Related Questions