我正在尝试初始化包含数组的结构数组。看着 this和 this, 我认为这是一个非常合理的尝试:
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 :(得分: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}
};