2015-12-27 82 views
1

我想初始化一個包含數組的結構數組。縱觀 thisthis, 我覺得一個非常合理的嘗試是這樣的:使用數組初始化結構數組作爲結構的元素

struct Score_t{ 
    int * dice; 
    int numDice; 
    int value; 
}; 
struct Score_t Scores[NUMSCORES] = { 
    [0]={{0,0,0},3,1000}, 
    [1]={{1,1,1},3,200}, 
    [2]={{2,2,2},3,300}, 
    [3]={{3,3,3},3,400}, 
    [4]={{4,4,4},3,500}, 
    [5]={{5,5,5},3,600}, 
    [6]={{0},3,100}, 
    [7]={{4},3,50} 
}; 

但是我不能得到這個編譯。你有什麼辦法來完成這個任務嗎?

編輯:忘記錯誤信息:(剪斷)

[5]={{5,5,5},3,600}, 
^
greed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default] 
greed.c:79:2: warning: initialization makes pointer from integer without a cast [enabled by default] 
greed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default] 
greed.c:79:2: warning: excess elements in scalar initializer [enabled by default] 
greed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default] 
greed.c:79:2: warning: excess elements in scalar initializer [enabled by default] 
greed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default] 
greed.c:80:2: warning: braces around scalar initializer [enabled by default] 
+0

什麼是錯誤信息? – Downvoter

+1

例如改變'[0] = {{0,0},3,1000},'爲'[0] = {(int []){0,0,0},3,1000},' – BLUEPIXY

+0

@BLUEPIXY就是這樣。你想提交這個答案,以便我可以接受嗎? – Hovestar

回答

3

int *不能{ }初始化(不匹配)
所以改變這樣。

struct Score_t Scores[NUMSCORES] = { 
    [0]={(int[]){0,0,0},3,1000}, 
    [1]={(int[]){1,1,1},3,200}, 
    [2]={(int[]){2,2,2},3,300}, 
    [3]={(int[]){3,3,3},3,400}, 
    [4]={(int[]){4,4,4},3,500}, 
    [5]={(int[]){5,5,5},3,600}, 
    [6]={(int[]){0},3,100}, //It doesn't know the number of elements 
    [7]={(int[]){4},3,50} //change to [7]={(int[3]){4},3,50} or [7]={(int[]){4},1,50} 
}; 
+0

注意:如果內部數組中的數字不會在運行時編輯,那麼在case中使用struct中的'const int *'和文字 –

+0

中的'(const int [])'',也可以更改'int *骰子;'。 – BLUEPIXY