我正在尝试创建一个 const 结构数组,但我不断得到
error initializer element is not a compile time constant
我使用的是keil IDE。 这很奇怪,因为我的结构是 const,这是一个示例:
typedef const struct{
CRGB color; // CRGB is another struct
void (*myfunc)(int);
}myProfile;
myProfile profile1 = { ....... }; // initialized struct
myProfile profiles[1] = { profile1 }; // error occurs here
即使我使用
const myProfile profile1 = { ..... };
初始化结构体时,我仍然遇到相同的错误。
我可以找到解决办法,但我真的很想了解发生了什么。谢谢。
最佳答案
发生错误的原因是您尝试使用变量初始化数组,该变量不是常量(=编译时已知的固定值),正如 M.M 在评论中提到的那样。
如果你想为你的结构创建一个默认值,你可以这样做 here .
基于该答案,您可以使用以下内容初始化一个表:
MyStruct instances[2] = {MyStruct_default, MyStruct_default};
这是一个快捷方式:
MyStruct instances[2] = { {.id = 3}, {.id = 3} };
请注意,对于由多个成员组成的结构,可以保留一些空白,并且大多数情况下应将它们设置为 0。
关于C 忽略结构体前面的 const 限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52978649/