I was wanting to see if I could write a decent linked list in C by myself and this code runs with 0 errors or warnings. The problem is that when I run the program and try to put in a name it crashes. I tried to debug it, but I am not too comfortable with the debugger. All I noticed was that it seemed to have a problem with my while(current->next!=null) lines, saying that there was an access violation. Any help would be appreciated. Thanks in advance. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
char name[80];
struct person *next;
};
typedef struct person PERSON;
typedef PERSON* LINK;
void add(LINK ptr, LINK data);
void remove(LINK ptr, char *name);
void print(LINK ptr);
int main()
{
LINK head=NULL;
LINK person=(PERSON*)malloc(sizeof(PERSON));
int selection=0;
char name[80];
printf("Hello. Enter your selection.\n");
while(1)
{
printf("1. Add\n2.Delete\n3.Print\n4.Exit\n");
fflush(stdin);
scanf("%d",&selection);
switch(selection)
{
case 1:
printf("Enter a name.\n");
fflush(stdin);
gets(name);
strcpy(person->name,name);
add(head,person);
break;
case 2:
printf("Enter the name you wish to delete.\n");
fflush(stdin);
gets(name);
remove(head,name);
break;
case 3:
print(head);
break;
case 4:
return 0;
default:
printf("Invalid selection.\n");
}
}
return 0;
}
void add(LINK head, LINK data)
{
//Puts the new entry in alphabetical order
LINK current=head;
LINK insert=data;
LINK previous=head;
while(current->next!=NULL)
{
if(strcmp(current->name,insert->name)>0)
{
insert->next=previous->next;
previous->next=insert;
break;
}
previous=current;
current=current->next;
}
}
void remove(LINK head, char *name)
{
LINK current=head;
LINK previous=current;
while(current->next!=NULL)
{
if(strcmp(current->name,name)==0)
{
previous->next=current->next;
free(current);
}
}
}
void print(LINK head)
{
LINK current=head;
while(current->next!=NULL)
{
printf("%s\n",current->name);
}
}



LinkBack URL
About LinkBacks



)