【问题标题】:Opaque Structure Pointer不透明结构指针
【发布时间】:2013-08-29 17:53:33
【问题描述】:

在我的库中,我有一个实例结构,其中包含库所需的所有内容,这样您就可以定义库的多个实例。该库要求用户定义自己的扩展或自定义变量。

这是我尝试过的:

图书馆.h

typedef struct custom_s *custom;

typedef struct {
    int a;
    int b;
    custom customs;
} instance;

然后用户可以这样做:

Main.c

// User sets their own custom structure
struct custom_s {
    int c;
};

int main(void) {
    instance test;
    test.customs.c = 1;
}

但是我收到“分段错误”的错误。

【问题讨论】:

    标签: c structure opaque-pointers


    【解决方案1】:

    不应该是:

    test.customs->c = 1

    因为你输入了它

    typedef struct custom_s *custom;

    并用作

    custom 在实例结构中。

    从不分配...

    【讨论】:

      【解决方案2】:
      typedef struct custom_s *custom;
      

      定义一个指向custom 结构的指针。在您的示例中,这是一个从未分配过的未定义指针,因此当您尝试访问它时会发生分段错误。

      不透明结构的一个副作用是客户端代码不知道大小。这意味着您必须创建自己的函数来分配/创建它们。

      制作类似的东西:

      instance test;
      test.customs = customs_create();
      test.customs.c = 1;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-17
        • 1970-01-01
        • 1970-01-01
        • 2016-06-30
        • 1970-01-01
        • 2011-07-15
        • 2011-02-12
        • 1970-01-01
        相关资源
        最近更新 更多