首页 > 解决方案 > 如果我不将辅助变量声明为全局,则链接列表不起作用

问题描述

我正在编写一个程序来创建一个单链表。我正在使用两个指针变量,其中一个被命名为“start”,它指向列表的第一个节点,另一个我正在使用的指针变量被命名为“t”。我使用这个指针作为辅助变量,它有助于遍历列表而不干扰开始。
该程序已成功编译,但我面临的问题是在运行时它只允许我将一个节点添加到列表中。之后,如果我尝试添加另一个节点,则在输入节点的数据后执行停止。
我尝试了几件事,但只有一个有效。如果我将“帮助指针变量”声明为全局,则程序开始运行良好。
为什么会发生这种情况?
我只在函数中使用辅助指针变量“t”来遍历列表,它甚至没有与程序中的另一个函数通信。

有人可以解释为什么它只适用于全局声明吗?

这是函数的代码->

void insert()
{

    struct node *newnode;
    struct node *t; //<------this is the helper variable if I declare this locally
                            //then the problem occurs in the run time.                                  
    newnode = create();
    printf("Enter data ");
    scanf("%d",&newnode->info); 
    //printf("Node info = %d",newnode->info);
    if(start==NULL) 
    {
        start=newnode;  <------ this is that start variable which is declared above globally
        start->next=NULL;
        t=newnode;
    }
    else
    {
        t->next=newnode;
        t=newnode;
        t->next=NULL;       
    }   
    printf("%d successfully added to the list.",newnode->info);
}

标签: cpointersdata-structureslinked-listglobal-variables

解决方案


函数开头的变量 t 是一个悬空指针,即它不能被取消引用。尝试将其放入 else 块之前t->next=newnode;

t = start;
while(t->next)
    t = t->next;

当您将其声明为全局(或静态工作)时,您会使其记住存储在其中的最后一个值,因此每次它不会以悬空指针启动。


推荐阅读