我使用双向链接列表编写经典的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
有什么问题,我不能真正访问下一个指针,但我不完全确定。
你能帮我吗?
可能设置tmp1->未来= NULL会有所帮助,或拨打释放calloc代替的malloc。并且不要强制malloc的返回值。 – bruceg
@bruceg为什么不投放malloc的返回?我很少看到它,但我的教授在做C讲座时坚持要这样做。 – user1662035
http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – bruceg