简体   繁体   English

使用数组初始化struct数组作为结构的元素

[英]Initializing struct array with arrays as elements of the struct

I am trying to initialize an array of structs that contain an array. 我正在尝试初始化包含数组的结构数组。 Looking at this and this , I think a pretty reasonable attempt is 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}
};

However I can't get this to compile. 但是我无法编译。 Do you have any ways to get this done? 你有办法完成这项工作吗?

Edit: Forgot the error message: (snipped) 编辑:忘记错误消息:(剪断)

  [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]

int * can't be initialized with { } (not match) int *无法用{ }初始化(不匹配)
So change to like this. 所以换成这样的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM