C 具有结构的代码的编译错误

C 具有结构的代码的编译错误,c,struct,C,Struct,我试着把这个复杂化: #define VAR_COUNT 5 typedef struct { uint32_t value; char name[10]; } variable; variable cfg[VAR_COUNT]; cfg[0].value = 0; cfg[0].name = "test"; 但是得到错误: src/variables.c:26:7: error: expected '=', ',', ';', 'asm' or '__attribute__' b

我试着把这个复杂化:

#define VAR_COUNT 5
typedef struct {
  uint32_t value;
  char name[10];
} variable;

variable cfg[VAR_COUNT];

cfg[0].value = 0;
cfg[0].name = "test";
但是得到错误:

src/variables.c:26:7: error: expected '=', ',', ';', 'asm' or '__attribute__' before '.' token
cfg[0].value = 0;
src/variables.c:27:7: error: expected '=', ',', ';', 'asm' or '__attribute__' before '.' token
cfg[0].name = "test";
这对我来说真是个意想不到的错误。我认为我的结构数组是错误的,但使用以下代码:

typedef struct {
  uint32_t value;
  char name[10];
} variable;

variable cfg;

cfg.value = 0;
cfg.name = "test";
我也犯了同样的错误

Upd:我添加了一个函数

void set (variable data, uint32_t value) {
  data.value = value;
}
在它的范围内,我可以毫无错误地使用structure元素


感谢大家,问题已经解决,在编写一些C代码之前,您应该始终保持完全清醒。您不能分配给数组,但可以复制到数组:

strcpy(cfg[0].name, "test");

语句必须位于函数内部。例如:

int main()
{
    cfg[0].value = 0;
    strcpy(cfg[0].name, "test");
}
语句在程序流到达该点时执行。函数外没有程序流;程序流从
main()
的开头开始

您可以在声明中,在函数之外使用初始值设定项(函数不是程序流的一部分,它们在流开始之前被设置为一个块):


这将以相同的顺序初始化所有内容;您也可以在这里使用指定的初始值设定项。

好的,但是为什么w/out array我会得到相同的错误?upd:我试图添加您的代码,但得到另一个错误:src/variables.c:26:8:错误:需要声明说明符或'cfg'strcpy(cfg[0].name,“test”);src/variables.c:26:21:错误:字符串常量strcpy(cfg[0].name,“test”)前应包含声明说明符或“…”@问题出在结构内部的数组
name
,而不是
cfg
数组。更重要的是,
cfg.value=0和朋友都需要在函数中。@PaulGriffiths,你说得对,我必须只在函数中使用结构@Anper:所有语句都必须在C中的函数中,而不仅仅是那些处理
struct
s的语句。
variable cfg[VAR_COUNT] = {
    { 0, "test" },
    { 5, "bar" },
    { 7, "tennis" }
};