Home Ask Login Register

Developers Planet

Your answer is one click away!

theamydance February 2016

C typedef coding style for opaque structs

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;

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


phoenix February 2016

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;

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
Forward declarations of unnamed struct

Post Status

Asked in February 2016
Viewed 1,191 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life