【问题标题】:Run Time Error in insert at beginning (head) function in a Doubly Linked List in C?在 C 中的双向链表中插入开头(头)函数时出现运行时错误?
【发布时间】:2021-12-27 10:50:22
【问题描述】:

请指出我的代码逻辑中的错误(如果有的话)。它是一个试图在 C 语言双向链表开头插入元素的函数。

struct DLL *insertAthead(struct DLL *head, int newData)
{
    struct DLL *p = (struct DLL *)malloc(sizeof(struct DLL *));
    p->prev = NULL;
    p->next = head;
    head->prev = p;
    p->data = newData;
    head = p;
    return head;
}

【问题讨论】:

    标签: c dynamic-memory-allocation doubly-linked-list


    【解决方案1】:
    struct DLL *p = (struct DLL *)malloc(sizeof(struct DLL *));
    

    应该是:

    struct DLL *p = malloc(sizeof(struct DLL));
                           ^^^^^^^^^^^^^^^^^^
    

    目前您只分配指针 (struct DLL *) 的大小,而不是 struct DLL 所需的任何大小。

    请注意,有些人喜欢这样写上面的内容:

    struct DLL *p = malloc(sizeof(*p));
    

    这可以说是更强大。

    请注意,我还删除了多余的演员表,这本身并不是一个错误,但这只是不必要的混乱and can in some cases be dangerous

    【讨论】:

    • 您能否详细说明为什么指针内存分配语句(在我的代码中)不起作用。我已经使用该语句格式很长时间了,直到此时它才产生问题。为什么从 malloc(struct DLL *) 中删除星号解决了问题?
    • @Ultimate 他在回答中告诉了你。你只为一个指针分配了速度,你想要一个结构 DLL 的空间
    猜你喜欢
    • 2016-07-26
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多