简体   繁体   English

不透明结构的C typedef编码样式

[英]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. 因此,我知道typedef对于不透明的结构是可以接受的,这些结构只能由访问器函数来操作。

Is this the appropriate way to use opaque typedef structs that are self referential within the accessor functions? 这是在访问器函数中使用自引用的不透明typedef结构的适当方法吗?

    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

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. struct foostruct foo的未命名struct typedef不同。 The previous stackoverflow answers clearly explain the reason: 前面的stackoverflow答案清楚地说明了原因:
Forward declaring a typedef of an unnamed struct 转发声明未命名结构的typedef
and
Forward declarations of unnamed struct 转发未命名结构的声明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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