Displaying the elements of a singly linked list
c
Solution
Declaring a pointer to a node (`start`) does not actually create the node itself - you need `malloc()` to do this. However, `malloc()` doesn't bother to fill the node with reasonable values, which is why you get a seemingly random value in `data`. Try `start->data = 42;` after `start->next = NULL;`.
Edit: See ArjunShankar's comment about not calling `malloc()` from outside a function.
Problem
I have written a simple program to traverse through the nodes of a linked list. ``` struct node { int data; struct node *next; }*start; start=(struct node *)malloc(sizeof(struct node)); start->next=NULL; int main(void) { if(start==NULL) { printf("There are no elements in the list"); } else { struct node *tmp; printf("\nThe elemnets are "); for(tmp=start;tmp!=NULL;tmp=tmp->next) { printf("%d\t",tmp->data); } } return 0; } ``` Whenever i am trying to print the elements of the linked list, however even though the list is empty, it gives the output ``` The elements are 5640144 ``` What am i doing wrong ? Am i declaring the start pointer correctly ? Why do i need to do this (actually i was not doing this initially, but was asked to by one of my friends) ``` start=(struct node *)malloc(sizeof(struct node)); start->next=NULL; ```