gpt4 book ai didi

c - 链表逻辑错误导致程序卡住

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:45 25 4
gpt4 key购买 nike

我正在尝试创建经典的贪吃蛇游戏(在 Linux 终端中),但我的链表和/或基本逻辑实现存在问题。我相当确定我的 move_snake() 方法是正确的 - 然而,在 grow_snake() 完成后,它添加了与检索到的奖杯值相同数量的节点,程序卡住了。我有一种感觉,这是因为我如何在 grow_snake() 类中分配我的指针,特别是在添加到蛇头之后,但我一直遇到这样的困难,我真的可以使用另一双眼睛在此刻。提前致谢。

move_snake()

// Moves the snake based on user input, via key press
void move_snake(){
struct snake_struct *temp_ptr = root;
struct snake_struct *last_node = malloc(sizeof(struct snake_struct *));
change_direction(ui); // Change direction on UI
draw_border(); // Clear screen & draw border
draw_trophy(); // Keep trophy on screen

// grow_snake();
check_position();

while(temp_ptr->next){
mvaddch(temp_ptr->y_pos, temp_ptr->x_pos, DEFAULT_SYMBOL);
last_node = temp_ptr;
temp_ptr = temp_ptr->next;
}

temp_ptr->x_pos = root->x_pos + x_dir;
temp_ptr->y_pos = root->y_pos + y_dir;
if(root->next != NULL)
temp_ptr->next = root;
last_node->next = NULL;
root = temp_ptr;


mvaddch(root->y_pos, root->x_pos, set_symbol());
refresh();
usleep(speed);
}

grow_snake()

// Grows the snake based on trophy value that was ate
void grow_snake(){

struct snake_struct *temp_ptr = root;
struct snake_struct *new_head = malloc(sizeof(struct snake_struct *));
change_direction(ui); // Change direction on UI
// int num_links = 2;
int num_links = trophy.value;
generate_trophy();
int i = 0;
draw_border(); // Clear screen & draw border
draw_trophy(); // Keep trophy on screen

while(temp_ptr->next){
mvaddch(temp_ptr->y_pos, temp_ptr->x_pos, DEFAULT_SYMBOL);
temp_ptr = temp_ptr->next;
}

for(i = 0; i < num_links; i++) {
new_head->x_pos = root->x_pos + x_dir;
new_head->y_pos = root->y_pos + y_dir;
new_head->next = root;
new_head->symbol = DEFAULT_SYMBOL;
root = new_head;
set_symbol();
change_direction(ui);
mvaddch(root->y_pos, root->x_pos, root->symbol);
refresh();
usleep(speed);
}
}

change_direction()

// Changes direction on user key input
void change_direction(char key_press){
if ((char) tolower(key_press) == 'w'){
if(y_dir == 1 && root->next){
alert(2);
}
else{
y_dir = -1;
x_dir = 0;
}
}
else if ((char) tolower(key_press) == 'a'){
if(x_dir == 1 && root->next){
alert(2);
}
else{
y_dir = 0;
x_dir = -1;
}
}
else if ((char) tolower(key_press) == 's'){
if(y_dir == -1 && root->next){
alert(2);
}
else{
y_dir = 1;
x_dir = 0;
}
}
else if ((char) tolower(key_press) == 'd'){
if(x_dir == -1 && root->next){
alert(2);
}
else{
y_dir = 0;
x_dir = 1;
}
}
}

最佳答案

grow_snake() 函数中,您的 malloc() 调用没有分配适当数量的字节。通过写作:

malloc(sizeof(struct snake_struct *));

您分配的是指向您的结构的指针的大小,而不是分配结构本身的大小。删除“*”并尝试使用

malloc(sizeof(struct snake_struct));

关于c - 链表逻辑错误导致程序卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34092183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com