我正在使用双向链表在C语言中编写经典的Snake游戏,并编写了一个函数,该函数创建一个指针,为结构分配所需的空间,然后为列表中的下一个指针分配内存,依此类推。最后,指向第一个元素的指针由函数返回,并且可以在主函数中分配给头指针。

开始游戏时,我希望蛇的长度为三,所以我在函数中具有三个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();
}

问题是,当我尝试访问main函数中列表的第二个元素时,游戏崩溃。我怀疑这是有问题的
for循环中的tmp1 = tmp1->next,我实际上并没有访问下一个指针,但我不确定。

你能帮我吗?

最佳答案

您有很多错误,表明您不太了解内存,变量和指针的工作方式。例如,在tmp1 = tmp1->next循环的末尾执行for,紧随其后的是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 = &current->next;
    }

    /* now return the pointer to the first element in list */
    return head;
}

关于c - 在for循环中初始化双链表会导致崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34935834/

10-10 21:28