Hi
I have created the the same program using functions,but this time it is not working.
Pointer head has null value.
I can understand that this is due to scoping problem,since head and other pointers are declared inside main and I am passing them as variable to functions.( Please correct me if I am wrong)
The alternate sol. can be that I declare head and other variable as global; but that will be a bad practice.
Can anybody help me to know how to do it?
The code I have wrote is:
Code:
#include<stdio.h>
#include<stdlib.h>
struct link
{
int data;
struct link *next;
};
void insert(static struct link *head)
{
struct link *temp,*node;
int info =0;
printf("\n Enter the number");
scanf("%d",&info);
node = (link *)malloc(sizeof(link));
if( head == NULL )
{
node->data = info;
node->next = NULL;
head = node;
}
else
{
temp = head;
while( temp->next != NULL )
temp=temp->next;
node->data = info;
node->next = NULL;
temp->next = node;
}
}
void display(static struct link *head)
{
struct link *temp;
temp = head;
while ( temp !=NULL ){
printf("\n %d",temp->data);
temp = temp->next;
}
}
int main()
{
struct link *head;
struct link *temp,*node;
node = NULL;
temp = NULL;
head = NULL;
int ch = 1;
while(ch)
{
printf("\n Enter your Choice");
printf("\n 1: Insert");
printf("\n 2: Display");
printf("\n 3: Exit");
scanf("%d",&ch);
switch(ch)
{
case 1:
insert(head);
break;
case 2:
display(head);
break;
case 3:
exit(0);
break;
}
}
}
Thanks