我在读一本算法书,发现自己陷入了困境。我创建了一个双链接列表,当我试图打印出它的内容时,它会打印出我认为是地址或其他一些与我想要的不相关的值。代码如下:

typedef struct double_element *dElement;
struct double_element
{
    int value;
    dElement prev;
    dElement next;
};

dElement createNewDListWithElements(int count)
{
    dElement element = malloc(sizeof(dElement));

    element->value = 1;
    element->next = NULL;
    element->prev = NULL;

    dElement previous = element;

    for (int i = 1; i < count; i++) {

        dElement el = malloc(sizeof(dElement));

        el->value = i;
        el->next = NULL;
        el->prev = previous;
        previous->next = el;

        previous = el;
    }

    return element;
}

void printDList(dElement node)
{
    printf("printing doubly linked list:\n");

    while (node) {

        printf("%i\n", node->value);

        node = node->next;
    }

    printf("end printing double linked list\n");
}

输出如下:
printing doubly linked list:
1
1070320
1070336
1070352
1070368
1070384
1070400
1070416
1070432
1070448
end printing double linked list

最佳答案

您的问题是您试图为struct double_element分配空间,但您只要求有足够的空间来存储struct double_element*

10-08 05:48