C typedef coding style for opaque structs

2019-08-09 20:15发布

问题:

So I understand that typedefs are acceptable for opaque structs that can only be manipulated by accessor functions.

Is this the appropriate way to use opaque typedef structs that are self referential within the accessor functions?

    typedef struct foo {
        struct foo *bar;
        int member;
    } foo1;

    foo1 * blah1 = (foo1*) malloc(...);
    blah1->bar->member = 999;

The alternative is this:

    typedef struct {
        struct foo* bar;
        int member;
    }foo; 

So when you do something like this:

    foo * blah1 = (foo*) malloc(...);
    blah1->bar->member = 999; 

You'll get this error:

    dereferencing pointer to incomplete type

回答1:

This question is similar to asking for forward declaration of unnamed struct. You cannot forward declare an unnamed struct and similarly, you cannot use it as a member in the same struct as you have shown:

typedef struct {
    struct foo* bar;
    int member;
}foo; 

This is because the compiler just cannot know the type. struct foo is not same as unnamed struct typedef to foo. The previous stackoverflow answers clearly explain the reason:
Forward declaring a typedef of an unnamed struct
and
Forward declarations of unnamed struct