初始化for循环中的双向链接导致崩溃
我使用双向链接列表编写经典的Snake游戏,并编写了一个函数,该函数创建一个指针,为结构分配所需空间,然后分配内存给列表中的下一个指针等等。最后,指向第一个元素的指针由函数返回,并且可以分配给主函数中的头指针。初始化for循环中的双向链接导致崩溃
当开始游戏时,我希望蛇的长度为3,所以我在函数中使用了三个malloc,并使用了指针,指针 - >下一个,指针 - >下一个 - >下一个等,并且一切正常。
由于很多步骤都在这个过程中,我认为把所有这一切到一个for循环这样的重复:
#include <stdio.h>
#include <stdlib.h>
typedef struct snake snake;
struct snake {
int x; /* x coordinate */
int y; /* y coordinate */
snake *previous;
snake *next;
};
snake *initSnake(void) {
snake *pointer, *tmp1, *tmp2 = NULL;
/* three iterations, so the snake will have a length of three */
for(int i = 0; i<3; i++, tmp1 = tmp1->next) {
if(NULL == (tmp1 = (snake*)malloc(sizeof(snake)))) {
return NULL;
}
/* coordinates */
tmp1->x = 20;
tmp1->y = 10 + i;
/* first previous points to NULL */
tmp1->previous = tmp2;
/* temporarily store last pointer to be used for next previous pointer */
tmp2 = tmp1;
if(0 == i) {
/* store first pointer so it can be returned */
pointer = tmp1;
}
}
/* the last next pointer has to point to NULL */
tmp1 = NULL;
/* now return the pointer to the first element in list */
return pointer;
}
int main() {
/* pointer to first element in list */
snake *head = NULL;
if(NULL == (head = initSnake())) {
fprintf(stderr, "Not enough memory!\n");
return EXIT_FAILURE;
}
/* here everything works fine */
printf("%d\n", head->y);
printf("%d\n", head->previous);
/* when trying to acces the content of the next element, the program crashes... */
printf("%d\n", head->next->x);
/* pause */
getchar();
}
的问题是,当我尝试访问的第二个元素主要功能内的列表,游戏崩溃。我怀疑在for循环中 tmp1 = tmp1->next
有什么问题,我不能真正访问下一个指针,但我不完全确定。
你能帮我吗?
你要最后下一个指针设置为NULL:
/* the last next pointer has to point to NULL */
tmp1->next = NULL; // -> next !
因为tmp1
是一个局部变量,将其设置为只返回时,将没有任何效果之前NULL。
编辑:
哎呀,也不for循环做tmp1 = tmp1->next
的:因为它没有设置此刻的你尝试执行此操作。您需要下一个与以前一起设置:
/* first previous points to NULL */
tmp1->previous = tmp2;
if (tmp2)
tmp2->next = tmp1;
但tmp1已经是列表中的最后一个' - >下一个指针',因为我将'tmp1'设置为' tmp1-> next',然后离开循环。 – user1662035
此刻你做了tmp1 = tmp1-> next,你从未设置过下一个值。看到我的编辑 – Christophe
实际上你的双链表只有单链接... – Christophe
你有很多暗示,你真的不知道如何记忆,变量&指针的工作失误。例如在for
循环结束时做tmp1 = tmp1->next
,紧接着tmp1 = (snake*)malloc(sizeof(snake))
覆盖tmp1
,并使之前的操作变得毫无意义。代码中的其他地方也有类似的操作。
要清理一下,试试这个:
snake *initSnake(void) {
snake *head, **current, *prev;
/* three iterations, so the snake will have a length of three */
for(int i = 0, prev = NULL, current = &head; i<3; i++) {
if(NULL == (*current = malloc(sizeof(snake)))) {
return NULL; /* note that if this happens midway
through allocation, nothing gets freed */
}
/* coordinates */
(*current)->x = 20;
(*current)->y = 10 + i;
/* next, previous pointers */
(*current)->next = NULL;
(*current)->previous = prev;
prev = *current;
current = ¤t->next;
}
/* now return the pointer to the first element in list */
return head;
}
可能设置tmp1->未来= NULL会有所帮助,或拨打释放calloc代替的malloc。并且不要强制malloc的返回值。 – bruceg
@bruceg为什么不投放malloc的返回?我很少看到它,但我的教授在做C讲座时坚持要这样做。 – user1662035
http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – bruceg