在我的库中,我有一个实例结构,其中包含库所需的所有内容,因此您可以定义库的多个实例。该库要求用户定义自己的扩展或自定义变量。
这就是我的尝试:
Library.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;
}
但是我收到“分段错误”的错误。
答案 0 :(得分:1)
不应该是:
test.customs->c = 1
因为您在
中输入了它 typedef struct custom_s *custom;
并用作
实例结构中的 custom
。
永远不会分配...
答案 1 :(得分:1)
typedef struct custom_s *custom;
定义指向custom
结构的指针。在您的示例中,这是一个永远不会分配的未定义指针,因此当您尝试访问它时会发生分段错误。
不透明结构的一个副作用是客户端代码不知道该大小。这意味着您必须创建自己的函数来分配/创建它们。
做类似的事情:
instance test;
test.customs = customs_create();
test.customs.c = 1;