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.
for (k = 0; k <= roundCount; k++)should bek < roundCountotherwise you index out of bounds forrounds[i][k]