【发布时间】:2016-11-01 11:22:46
【问题描述】:
我有一个大对象,其中有几个字段是 const 数组,看起来像这样:
struct test {
const int vals[99999999];
};
我想使用指定的初始化器来创建结构,因为真正的结构有很多字段。
结果,我尝试了这个
#include <stdlib.h>
struct test {
const int vals[99999999];
};
int main()
{
struct test first = {.vals[4]=4};
return 0;
}
不出所料,这在运行时会失败,因为结构太大而无法放入堆栈。
然后我尝试了
#include <stdlib.h>
struct test {
const int vals[99999999];
};
int main()
{
struct test * t = malloc(sizeof(struct test));
*t = (struct test){.vals[4]=4 };
return 0;
}
当我编译它时,这反而失败了:
test.c:9:8 error: assignment of read-only location '*t'
是否可以使用指定的初始化器来创建这个结构?
【问题讨论】:
-
如果你打算稍后赋值,为什么数组需要
const? -
@usr 我只在初始化时赋值