2

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.

Codesmith
  • 5,779
  • 5
  • 38
  • 50

2 Answers2

5

You need a forward declaration to make the type known:

struct B;
struct A {
    B* pBstruct;
};
struct B {
    A* pAstruct;
};
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • Agree for C++ it solves the problem. If it was pure C, maybe need an additional key word: struct B* pBstruct; – digit plumber Nov 20 '12 at 00:58
  • Yes, for C, either `struct B* pBstruct;` or `typedef struct A A; typedef struct B B;` is needed. But since the question was only tagged C++, I didn't add the C way. – Daniel Fischer Nov 20 '12 at 01:05
  • That's totally cool as it's tagged C++. Well for me the moment I saw struct, I recalled the subtlety of the syntax difference. – digit plumber Nov 20 '12 at 01:09
2

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;
    };
Codesmith
  • 5,779
  • 5
  • 38
  • 50