我有以下代码:
测试.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
需要一个指向非 const 的指针,struct test
我不确定为什么 GCC 认为我正在尝试修改只读变量。在我看来,我只是将类型的文字按位分配给struct test
(堆栈)变量t
,并且标记结构的字段似乎无关紧要const
。const
GCC 将在删除时编译正常。这里发生了什么?