dhysong
dhysong

Reputation: 1021

Global multidimensional array of a struct in c

I'm trying to build a simple tournament in c, but I'm struggling to use a multidimensional array of struct round.

typedef struct round{
   enum role  myrole;
   int *opponent;
   int flag;
} *round_t;

static round_t** rounds;

void buildTournament(int players){
   int roundCount = ceil_log2(players);

   rounds = malloc( players * sizeof *rounds );

   size_t row;
   for (row = 0; row < roundCount; ++row)
       rounds[row] = malloc( roundCount * sizeof **rounds );

   int i;
   for (i = 0; i < players; i++)
   {
        for (k = 0; k <= roundCount; k++)
        {
            round_t round = malloc(sizeof(round_t));
            if(i % 2 == 0)
            {
                round->myrole = WINNER;
            }
            else
            {
                round ->myrole = LOSER;
            }
            rounds[i][k] = round;
        }
   }

}

With 8 players, it throws a seg fault writing to rounds[3][0], which is the 10th memory location. This makes me think I'm only allocating 9 memory locations to the array. Obviously, I'm new to C, so any help would be very appreciated.

Upvotes: 0

Views: 37

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53046

You are not allocating enough space here

round_t round = malloc(sizeof(round_t));

your fault is that you declared round_t as a pointer to a struct round which hides the fact that round_t is struct round * from you, hence sizeof(round_t) seemed natural but it's wrong because it's allocating space for a pointer, and not for a strcut, change it like this

round_t round = malloc(sizeof(*round));

or

round_t round = malloc(sizeof(struct round));

Don't typedef pointers it makes your code very confusing, and if you must typedef a pointer, try to imply that it is a pointer in it's name, something like

typedef struct round{
    enum role  myrole;
    int *opponent;
    int flag;
} round_t;
typedef round_t *round_p;

and also, as @rpattiso commented, you should fix the for loop condition.

Upvotes: 1

Related Questions