我想初始化一个我已经制作的结构,但是我得到了错误,我无法理解导致它们的原因。 我正在使用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};
答案 0 :(得分:3)
您正在做的是分配后初始化。你不能分配这样的数组。
你可以做的是 -
instructions instructionData = {{"mov", "cmp" ... }, {0, 1, 2, ... }, {2, 2 ,2 ... }};
这会在定义中初始化整个结构。
同时如果你的struct有其他你没有初始值的字段,你可以使用指定的初始化器 -
instructions instructionData = {.codes={0, 1, 2, ... }};
这会将所有其他字段初始化为相应类型的默认初始值,例如NULL
用于指针,0
用于整数等。
如果您必须在初始化后分配单个非标量字段,则可以使用memcpy
作为
memcpy(instructionData.name, &({"mov", "cmp" ... }), sizeof(({"mov", "cmp" ... })));
你也可以使用sizeof (instructionData.name)
,但是你必须确保你的初始化程序至少和字段一样长。