c语言 - 如果我不将辅助变量声明为全局变量,链表不起作用



我正在编写一个程序来创建一个单链表。我使用两个指针变量,其中一个命名为"start",指向列表的第一个节点,另一个指针变量命名为"t"。我使用这个指针作为辅助变量,它有助于在不干扰开始的情况下遍历列表
程序成功编译,但我面临的问题是,在运行时,它只允许我向列表中添加一个节点。之后,如果我尝试添加另一个节点,则在输入该节点的数据后执行将停止
我试了几件事,但只有一件有效。如果我将"helper指针变量"声明为全局变量,程序就会正常运行
为什么会这样
我只是在函数中使用辅助指针变量"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);
}

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

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

当您将其声明为全局(或静态也有效(时,您会让它记住存储在其中的最后一个值,因此每次它都不会使用悬挂指针启动。

最新更新