Code:
#include<stdio.h>
#include<malloc.h>
struct details{
char *name;
int no;
struct details *info;
};
//ADDING THE LINKED LIST
void add(struct details **info,int no,char * name){
struct details *temp=malloc(sizeof(struct details));
temp = *info;
if(temp == NULL){
temp = malloc(sizeof(struct details));
}
else{
if(temp->info == NULL){
temp->info = malloc(sizeof(struct details));
temp = temp->info;
}
}
temp->no = no;
temp->name = name;
}
//DISPLAYING THE LINKED LIST
void display(struct details *info){
while(info!=NULL){
printf("\nThe List is:\n","\n no: \tname:\n","%d","%s and link:%d",info->no,info->name,info->info);
info = info->info;
}
}
//MAIN PROGRAM
int main()
{
struct details* ptr;
char *name,ch;
int no;
int select_option;
ptr = NULL;
printf("\n ***MAIN MENU*** \n1.Add Element \n2.Delete Element \n3.Search Element \n4.Linked List Concatenation \n5.Invert Linked List \n6.Diplay Elements \n Please Enter your choice:(eg:1,2,3,4,5,6)\n");
scanf("%d",&select_option);
do{
switch(select_option){
case 1:
printf("Enter no to add:");
scanf("%d",&no);
printf("Enter name to add:");
scanf("%s",name);
add(&ptr,no,name);
break;
case 6:
display(ptr);
break;
default:
printf("INVALID CHOICE!");
break;
}
printf("Do u wish to continue?(y/n):");
scanf("%c",&ch);
}while(ch == 'y' || ch == 'y');
return 0;
}
I'm trying to write a simple program using a linked list to add and display data. But its throwing me a segmentation fault. I hope that I have initialized all the pointers with the memory. All help appreciated.