C -初始化包含数组成员的结构时出错

v1l68za4  于 2023-04-05  发布在  其他
关注(0)|答案(1)|浏览(103)

我想初始化一个我做的结构,但我得到错误,我无法理解是什么导致他们。我正在与ANSI C标志GCC工作。
如果有人能帮助我了解问题所在,我将非常感激!

typedef struct _inst {
   const char *name[NUM_OF_INSTRUCTIONS];
   int codes[NUM_OF_INSTRUCTIONS];
   int validParam[NUM_OF_INSTRUCTIONS];    
 } instructions;

instructions instructionsData;

instructionsData.name[] = {"mov", "cmp", "add", "sub", "not", "clr", "lea", "inc", "dec", "jmp", "bne", "red", "prn", "jsr", "rts", "stop"};
instructionsData.codes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
instructionsData.validParam[] = {2, 2, 2, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0};

我从gcc得到的错误是:

dataStructs.h:47:17: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
 instructionsData.name[] = {"mov", "cmp", "add", "sub", "not", "clr", "lea", "inc", "dec", "jmp", "bne", "red", "prn", "jsr", "rts", "stop"};
                 ^
dataStructs.h:47:140: warning: ISO C does not allow extra ‘;’ outside of a function [-Wpedantic]
 instructionsData.name[] = {"mov", "cmp", "add", "sub", "not", "clr", "lea", "inc", "dec", "jmp", "bne", "red", "prn", "jsr", "rts", "stop"};
                                                                                                                                            ^
dataStructs.h:48:17: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
 instructionsData.codes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
                 ^
dataStructs.h:48:82: warning: ISO C does not allow extra ‘;’ outside of a function [-Wpedantic]
 instructionsData.codes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
                                                                                  ^
dataStructs.h:49:17: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
 instructionsData.validParam[] = {2, 2, 2, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0};
                 ^
dataStructs.h:49:81: warning: ISO C does not allow extra ‘;’ outside of a function [-Wpedantic]
 instructionsData.validParam[] = {2, 2, 2, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0};
qyswt5oh

qyswt5oh1#

你所做的是一个初始化后的赋值,你不能像那样给数组赋值.
你能做的是-

instructions instructionData = {{"mov", "cmp" ... }, {0, 1, 2, ... }, {2, 2 ,2 ... }};

这将初始化定义中的整个结构。
同时,如果你的结构体有其他没有初始值的字段,你可以使用指定的初始化器-

instructions instructionData = {.codes={0, 1, 2, ... }};

这会将所有其他字段初始化为相应类型的默认初始值,如指针的NULL,整数的0等。
如果在初始化后必须分配单个非标量字段,则可以使用memcpy作为

memcpy(instructionData.name, &({"mov", "cmp" ... }), sizeof(({"mov", "cmp" ... })));

你也可以使用sizeof (instructionData.name),但你必须确保你的初始化器至少和字段一样长。

相关问题