简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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