我正在使用 C 开发一个四连线游戏模拟器。
https://en.wikipedia.org/wiki/Connect_Four
第一步是为游戏创建棋盘环境。我继续创建了一个数据类型 board_t,它是一个包含动态大小数组的结构,该数组将保存在一维数组中播放的 Action 。 Board_t 还包括板的高度和宽度信息,因此可以以正确的方式检索东西。
我在 board_create() 函数中初始化这个棋盘,并在 board_can_play() 函数中使用这个初始化的 board_t 变量来检查在给定的游戏中是否可以进行任何游戏。这是代码。
#include <stdlib.h>
#include <assert.h>
#define PLAYER_BLUE 2
#define PLAYER_YELLOW 1
#define PLAYER_EMPTY 0
typedef unsigned char player_t;
typedef struct board_t
{
unsigned int width;
unsigned int height;
unsigned int run;
player_t * moves;
} board_t;
bool board_create (board_t ** b, unsigned int height, unsigned int width, unsigned int run, const player_t * i)
{
//Declare a board_t variable temp_b where parameters will be saved.
board_t temp_b;
//Create a pointer and malloc a memory location based on width and height.
temp_b.moves = malloc(sizeof(unsigned char)*(height*width));
//Itereate through the moves and initialize with the given player_t
int j;
for (j = 0; j < width*height; j++)
{
temp_b.moves[j] = PLAYER_EMPTY;
}
//Input all the values to temp_b
temp_b.height = height;
temp_b.width = width;
temp_b.run = run;
//Make a temporary pointer and assign that pointer to *b.
board_t * temp_b_ptr = malloc(sizeof(board_t));
temp_b_ptr = &temp_b;
*b = temp_b_ptr;
return true;
};
/// Return true if the specified player can make a move on the
/// board
bool board_can_play (const board_t * b, player_t p)
{
unsigned int i;
unsigned int height = board_get_height(b);
unsigned int width = board_get_width(b);
for(i = (height-1)*width; i < height*width; i++)
{
if (b->moves[i] == PLAYER_EMPTY)
{
return true;
}
}
return false;
}
但是,每当我从 board_can_play() 调用 board_t *b 时,程序都会出现段错误。更具体地说,
if (b->moves[i] == PLAYER_EMPTY)
这一行给我一个段错误。此外,在 main() 中运行良好的函数在 board_can_play() 中不起作用。例如,
unsigned int height = board_get_height(b);
unsigned int width = board_get_width(b);
应该得到 3 和 3,但得到 2 和 419678?我现在花了大约 7 个小时弄清楚,但无法弄清楚发生了什么。
最佳答案
在出现段错误的 if
语句中,
if (b->moves[i] == PLAYER_EMPTY)
问题不是 moves
是如何分配的,而是 b
本身是如何分配的。在 board_create()
中,您将在此处返回一个临时对象:
board_t * temp_b_ptr = malloc(sizeof(board_t));
temp_b_ptr = &temp_b;
*b = temp_b_ptr;
malloc
的指针丢失了(您正在覆盖它)并且只是返回(通过 *b
)一个指向局部变量的指针。
因此将分配移动到顶部并使用 temp_b_ptr
而不是 temp_b
:
board_t *temp_b_ptr = malloc(sizeof(board_t));
if( !temp_b_ptr ) {
/* error handling */
}
....
....
*b = temp_b_ptr;
关于C:无法在另一个函数中访问动态大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33713224/