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]
6
  • What's the error message? Commented Dec 27, 2015 at 22:45
  • 1
    E.g change [0]={{0,0,0},3,1000}, to [0]={(int[]){0,0,0},3,1000}, Commented Dec 27, 2015 at 22:51
  • @BLUEPIXY that was it. Do you want to submit that as an answer so I can accept it? Commented Dec 27, 2015 at 22:52
  • 1
    Entries 6 and 7 seem incorrect: numDice is 3, but there is only 1 die. Commented Dec 27, 2015 at 22:59
  • @BLUEPIXY, I learnt this new method from this post. I have one query. Do we need to manually free the allocation done as per above method? Commented Dec 28, 2015 at 5:11

1 Answer 1

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}
};
Sign up to request clarification or add additional context in comments.

2 Comments

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
in the case, also change int * dice;.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.