我正在尝试用c构建一个简单的锦标赛,但我正在努力使用一个多维数组的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;
}
}
}
对于8名玩家,它会抛出一个段错误写入回合[3] [0],这是第10个记忆位置。这让我觉得我只是为阵列分配了9个内存位置。显然,我是C的新手,所以任何帮助都会非常感激。
答案 0 :(得分:1)
你没有在这里分配足够的空间
round_t round = malloc(sizeof(round_t));
你的错是你宣称round_t
是指向struct round
的指针,它隐藏了round_t
struct round *
sizeof(round_t)
的事实,因此round_t round = malloc(sizeof(*round));
似乎自然但它错了,因为它为指针分配空间,而不是为strcut,改变它就像这样
round_t round = malloc(sizeof(struct round));
或
typedef
不要typedef
指针会让你的代码非常混乱,如果你必须typedef struct round{
enum role myrole;
int *opponent;
int flag;
} round_t;
typedef round_t *round_p;
一个指针,试着暗示它是一个指针,它的名字,某事像
for
并且,如@ rpattiso所述,您应该修复{{1}}循环条件。