C中的奇数错误; 期待什么

tek*_*agi 0 c variables

我在C中写一个小语言,它需要变量设置.我有一个变量表设置,但我收到一个奇怪的错误.

#define VAR_SIZE 100
typedef struct {
    const char *key;
    int value;
} variable;

variable Table[VAR_SIZE];
Table[0].key = NULL;
Table[0].value = 0;
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到以下错误:

stack.c:8: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
stack.c:9: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

Ada*_*eld 7

您正在尝试在全局范围内编写代码.你不能这样做.您需要为全局变量提供静态初始化程序,或者在函数调用内的运行时初始化它.

静态初始化程序的示例:

variable Table[VAR_SIZE] = {
    {NULL, 0},  // index 0
    {NULL, 0},  // index 1
    // etc.
};
Run Code Online (Sandbox Code Playgroud)

在运行时初始化:

variable Table[VAR_SIZE];

void init_table(void) {
    Table[0].key = NULL;
    Table[0].value = 0;
    // etc.
}

int main(int argc, char **argv) {
    init_table();
    // rest of program
}
Run Code Online (Sandbox Code Playgroud)

如果您在C99模式下编译,您还可以使用指定的初始值设定项:

// The following is valid C99, but invalid C89 and invalid C++
variable Table[VAR_SIZE] = {
    [0] = {   // initialize index 0
        .key = NULL,
        .value = 0
    },
    // etc.
};
Run Code Online (Sandbox Code Playgroud)