1

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]
Cœur
  • 37,241
  • 25
  • 195
  • 267
Hovestar
  • 1,544
  • 4
  • 18
  • 26

1 Answers1

3

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}
};
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • note: if the numbers in the inner array are not going to be edited at runtime, use `const int *` in the struct and `(const int[])` in the literal – M.M Dec 28 '15 at 00:00
  • in the case, also change `int * dice;`. – BLUEPIXY Dec 28 '15 at 00:06