不透明结构的 C typedef 编码风格

标签 c struct styles typedef

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

这是在访问器函数中使用自引用的不透明 typedef 结构的合适方法吗?

    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; 

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

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

你会得到这个错误:

    dereferencing pointer to incomplete type

最佳答案

这个问题类似于要求未命名结构的前向声明。 你不能转发声明一个未命名的结构,同样,你不能将它用作你所展示的同一结构中的成员:

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

这是因为编译器无法知道类型。 struct foo 与未命名的 struct typedef to foo 不同。 之前stackoverflow的回答都清楚的说明了原因:
Forward declaring a typedef of an unnamed struct

Forward declarations of unnamed struct

关于不透明结构的 C typedef 编码风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245615/

相关文章:

比较两个字符串,strcmp 的问题

c - 使用 sscanf 时出现段错误

c++ - 这属于什么 C++ 风格的语法

css - 如何应用背景渐变样式css

android - 使用 ActionBarSherlock 设置 tabBar-indicator 样式

c++ - 如何在 Linux 中打开包含非 Ascii 字符串的 wchar_t* 文件?

c - 如何让这个 C 宏工作?

c - 结构体元素的值在返回之前设置,但不在返回时设置

c++ - 访问私有(private)类 C++ 内部的结构

c - c中结构中的动态分配内存