不透明结构的 C typedef 编码风格 [英] C typedef coding style for opaque structs

查看:33
本文介绍了不透明结构的 C typedef 编码风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我理解 typedef 对于只能由访问器函数操作的不透明结构是可以接受的.

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 struct foo {
        struct foo *bar;
        int member;
    } foo1;

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

替代方案是这样的:

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

所以当你做这样的事情时:

So when you do something like this:

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

你会得到这个错误:

    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; 

这是因为编译器无法知道类型.struct foo 与 unnamed struct typedef to foo 不同.之前的stackoverflow回答清楚地说明了原因:
转发声明未命名结构的 typedef

未命名结构的前向声明

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

这篇关于不透明结构的 C typedef 编码风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆