Search code examples
cstructtypedefforward-declaration

How to forward declare structs in C


I want to doubly link a parent to a child struct. This I know works in C++.

struct child;

struct parent{
   child* c;
} ;

struct child{
   parent* p;
} ;

, but in C with typedefs I can't make it work without warnings.

struct child;

typedef struct {
    struct child* c;
} parent;

typedef struct {
    parent* p;
} child;

int main(int argc, char const *argv[]){
    parent p;
    child c;
    p.c = &c;
    c.p = &p;
    return 0;
}

gives me warning: assignment to ‘struct child *’ from incompatible pointer type ‘child *’. Is the first child struct then overwritten, or are there two distinct data structures now struct child and child?

Is this even possible in C? My second thought would be using a void* and cast it to child everywhere, but either option leaves a sour taste in my mouth so far.


Solution

  • The problem is that you have two different structures. The first one is

    struct child;
    

    and the second one is an unnamed structure with the alias name child

    typedef struct {
        parent* p;
    } child;
    

    You need to write

    typedef struct child {
        parent* p;
    } child;