Linked list not working if I don't declare the helper variable as global

ansme :

I'm writing a program to create a singly linked list. I'm using two pointer variables one of them is named as "start" which points to the first node of the list and the other pointer variable that I'm using is named as "t". I'm using this pointer as a helper variable which helps in traversing the list without disturbing the start.
The program gets successfully compiled, but the problem I'm facing is that during run time it only allows me to add one node to the list. After that, if I try to add another node, the execution stops after entering the data of the node.
I tried a couple of things, but only one of them worked. If I declare the "helper pointer variable" as global the program starts running fine.
Why is this even happening?
I'm only using the helper pointer variable "t" in a function to traverse the list and it's not even communicating with another function in the program.

Can someone please explain why it only works with global declaration?

This is the code of the function ->

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);
}
Adnesh Dhamangaonkar :

The variable t at the start of the function is a dangling pointer i.e. it can not be de-referenced. Try putting this in else block before t->next=newnode;

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

When you declare it as global (or static works too), you make it remember the last value which was stored in it, thus every time it does not initiate with a dangling pointer.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29054&siteId=1