#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
void insert_last(struct node **head, int value)
{
struct node* new = malloc(sizeof(struct node));
new->data = value;
if( !*head )
{
new->link = NULL;
*head = new;
}
else
{
struct node* last = *head;
while(last->link)
{
last = last->link;
}
new->link = NULL;
last->link = new;
}
}
struct node *head;
int main()
{
insert_last( & head, 5);
insert_last( & head, 10);
insert_last( & head, 15);
printf("%d ", head->data);
printf("%d ", head->link->data);
printf("%d ", head->link->link->data);
}
If I Declare struct node *head inside of the main the programm is not working.
what is the reason ?
> if i declare globally its working, otherwise not working.
> I repeating question because stackoverflow asking add more details(> If I Declare struct node *head in side of the main the programm is not working.
what is the reason ?
> if i declare globally its working, otherwise not working.)
CodePudding user response:
There is a initialization bug: In insert_last(), the variable head is tested without having been initialized explicitely. If head is declared as global, it is located in a global section that is most probably initialized to 0 by the loader (when the program is started); if head is declared in the function main() then it is located in the stack of the function and is not set to 0.