c - C中的指针N链表

标签 c pointers linked-list

我写了以下不起作用的代码。应用程序在 print 方法上崩溃。 知道哪里出了问题吗?

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int item;
    struct LinkedList *Next;
} LinkedList;

int main()
{
    LinkedList vaz;
    vaz.item = 14123;
    vaz.Next = 0;
    add(&vaz,123);
    add(&vaz,9223);
    Print(&vaz);
    return 0;
}
void Print(LinkedList* Val)
{
    if(Val != 0){
        printf("%i\n",(*Val).item);
        Print((*Val).Next);
    }
}
void add(LinkedList *Head, int value)
{
    if((*Head).Next == 0 )
    {
        LinkedList sab;
        sab.item = value;
        sab.Next = 0;
        (*Head).Next = &sab;
    }
    else{
       add((*Head).Next,value);
    }
}

最佳答案

您的 add 方法应该动态分配内存,您正在使用自动分配(局部变量),当您“离开”该函数时,它会被释放。当您稍后尝试访问此内存时,这将导致未定义的行为。

void add(LinkedList *Head, int value)
{
    if((*Head).Next == 0 )
    {
        LinkedList sab; <-- need to be allocated dynamically
        sab.item = value;
        sab.Next = 0;
        (*Head).Next = &sab;
    }
    else{
       add((*Head).Next,value);
    }
}

关于c - C中的指针N链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762488/

相关文章:

c++ - C语言上 "static const char array"可以包含变量的成员吗

c - PIC18F45K22内部振荡器频率问题

常量增量

java - 不将所有元素添加到链表中

c++ - 在复制节点后删除经典节点结构时,我们是否必须担心可能的覆盖?

c - 谜题: "[] is symmetric"?

c - 多线程初始化中的Unknown Segmentation Fault (Core Dumped)

c - C 中的指针 : why is the * needed in *address_of_x = &x when getting the address of x?

c - 反转字符串时获取 "Segmentation fault Core Dumped Error "

c - 为什么我的循环仅适用于前几次迭代?