简体   繁体   中英

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.

You can declare the structs then typedef them later:

struct child {
    struct parent* p;
};

struct parent {
    struct child* c;
};

typedef struct parent parent;
typedef struct child child;

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

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;

You can declare structures like this:

typedef struct parent {
    struct child* c;
}parent;

typedef struct child {
    parent* p;
}child;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM