2017-08-21 88 views
-5

我想初始化一個我已經做過的結構,但是出現錯誤,我無法理解造成它們的原因。 我正在使用ANSI C標誌工作在GCC上。C - 初始化數組成員結構時出錯

如果有人能幫助我理解問題所在,我將非常感謝!

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}; 
+7

您能否複製粘貼代碼並且不要發佈屏幕截圖? –

+0

dupe? https://stackoverflow.com/a/41510479/2173917 –

+0

@SouravGhosh雖然解決方案是相同的,我認爲問題是不同的。不是一個愚蠢的? –

回答

3

你在做什麼是一個賦值後初始化。你不能像這樣分配數組。

什麼可以代替做的是 -

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),但是您必須確保您的初始化程序至少與字段一樣長。

+0

你很害怕*? ;) –

+0

@FelixPalmen我很確定*;) –

+0

謝謝,現在正在編譯! 但我仍然不明白是什麼問題... – CrazyPhrog