C中的指针N链表 [英] pointers N linked list in C

查看:33
本文介绍了C中的指针N链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下无效的代码.应用程序在打印方法上崩溃.知道哪里出了问题吗?

I wrote to following code which does not work. The application crashes on the print method. Any idea where it goes wrong?

#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方法应该动态分配内存,您使用的是自动分配(局部变量),当您离开"时会释放该分配功能.当您稍后尝试访问此内存时,这将导致未定义的行为.

Your add method should allocate memory dynamically, you are using automatic allocation (local variables), which is freed when you 'leave' the function. This will cause an undefined behavior when you try to access this memory later on.

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中的指针N链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆