【发布时间】:2014-09-28 10:00:43
【问题描述】:
我有以下代码:
test.c
struct test {
int const i;
};
void init_test(struct test *t)
{
*t = (struct test){42};
}
int main(int argc, char **argv)
{
(void)argc; (void)argv;
struct test t;
init_test(&t);
/* I would expect t={42} here */
}
使用gcc -std=c99 -Wall test.c -o test 编译失败并出现以下错误:
error: assignment of read-only location '*t"
*t = (struct test){42}
^
而使用clang -std=c99 -Wall test.c -o test 编译成功并且生成的可执行文件按预期运行。首先,我的示例代码格式正确吗?由于函数 init_test 需要一个指向非常量 struct test 的指针,我不确定为什么 GCC 认为我正在尝试修改只读变量。在我看来,我只是将struct test 类型的文字按位分配给(堆栈)变量t,并且结构的字段标记为const 似乎无关紧要。当const 被删除时,GCC 将编译得很好。这是怎么回事?
【问题讨论】:
-
void foo(struct bar { const int n; } b1, struct bar b2) { b1 = b2; }也重现了该问题(clang 警告结构定义仅在此函数中可见,这很好但在这里无关)。 -
可能重复:stackoverflow.com/questions/18527984/… -- 看起来像一个错误(但我找不到错误报告)。你能给出你的clang版本吗?也许下载最新版本再试一次。
标签: c c99 compound-literals