Was reading c guides on dynamic memory allocation functions.. and tried to write a program creating a linked list, to back up the knowledge... and i failed miserably :p can't figure out why it keeps giving me segmentation faults >.<
i figured the scanf's are the cause.. but don't understand why ;o
I'd appreciate if someone could point my mistake out to me ;)
here's the source:
Code:#include <stdio.h>
#include <stdlib.h>
struct record{
char name[15];
int age;
struct record *next;
};
struct record *create_list(){
char answer='y';
struct record *head;
struct record *new_entry;
while(answer!='n'){
if(!head){
new_entry=(struct record*)malloc(sizeof(struct record));
printf("Name:\n");
scanf("%s",new_entry->name);
printf("Age:\n");
scanf("%i",new_entry->age);
new_entry->next=NULL;
head=new_entry;
}
else{
new_entry=(struct record*)malloc(sizeof(struct record));
printf("Name:\n");
scanf("%s",new_entry->name);
printf("Age:\n");
scanf("%i",new_entry->age);
new_entry->next=head;
head=new_entry;
}
printf("Would you like to add another entry? [y/n]");
scanf("%c",answer);
}
return head;
}
void print_list(struct record *current){
while(!current->next){
printf("%s is %i years old\n", current->name, current->age);
current=current->next;
}
}
void free_list(struct record *current){
struct record *temp;
while(!current->next){
temp=current->next;
printf("%s deleted..",current->name);
free(current);
current=temp;
}
}
int main(){
struct record *start;
start=create_list();
print_list(start);
free_list(start);
}
