我有这两种结构:
struct Params {
int a;
int b;
};
struct Foo {
const struct Params settings;
int state;
};
settings
成员是一个提示,一旦创建并初始化struct Foo
,就不应该更改它。
我想动态分配这个结构,例如
struct Foo * new_foo(void)
{
struct Foo *n = malloc(sizeof *n);
if (n) {
n->settings.a = SETTING_A;
n->settings.b = SETTING_B;
...
}
return n;
}
现在,由于设置为const,因此无法编译。什么是正确的方法 以这种方式初始化这样的结构?或者最好不将设置成员声明为const?
答案 0 :(得分:1)
分配内存(因而不是常量),因此将const
强制转换是合法的:
struct Foo * new_foo(void)
{
struct Foo *n = malloc(sizeof *n);
if (n) {
struct Params *s = (void *)&n->settings;
s->a = SETTING_A;
s->b = SETTING_B;
}
return n;
}
答案 1 :(得分:0)
这是一种方法:
struct Foo *new_foo(void)
{
static struct Foo foo =
{
.settings =
{
.a = SETTING_A,
.b = SETTING_B
},
.state = ...
};
struct Foo *n = malloc(sizeof *n);
memcpy(n, &foo, sizeof *n);
return n;
}
这是另一种方法:
struct Foo *new_foo(void)
{
static struct Params settings =
{
.a = SETTING_A,
.b = SETTING_B
};
struct Foo *n = malloc(sizeof *n);
memcpy((struct Params*)&n->settings, &settings, sizeof settings);
n->state = ...;
return n;
}