Hi,
I have create a simple program for displaying a link list,but it is not working properly.
The code is as follow:
Code:
#include<stdio.h>
#include<stdlib.h>
struct linklist
{
int data;
struct linklist *next;
};
struct linklist *ptr;
void insert(linklist *ptr)
{
printf("INSIDE INSERT%u",ptr );
int num;
struct linklist *temp = ptr;
struct linklist *node = (struct linklist *)malloc(sizeof(struct linklist));
printf("\n Enter the data \n");
scanf("%d",&num);
node->data = num;
if ( ptr == NULL ) {
printf("INSIDE IF%u",ptr );
ptr = node;
node->next = NULL;
}
else {
printf("INSIDE ELSE");
while ( temp->next != NULL ) {
temp = temp->next;
}
temp->next = node;
node->next = NULL;
}
}
void display(linklist *ptr)
{
struct linklist *temp = ptr;
while ( temp != NULL ) {
printf("%d",temp->data );
temp = temp->next;
}
}
int main()
{
ptr = NULL;
int ch;
while ( 1 ) {
switch ( ch ) {
case 1:
insert(ptr);
break;
case 2:
display(ptr);
break;
case 3:
exit(0);
}
printf("\nEnter your choice ");
scanf("%d",&ch);
}
}
The problem is that in insert(ptr) function it always showing the ptr value 0 i.e NULL which I don't understand since the ptr I have declared as global so it should not be initialized to 0 every time the loop runs.
Can anybody explain me the behavior and solution to it.
Thanks