I have recently started to learn about linked lists and I was wondering 2 things about my code:
Why does the program crash?
Why does it type every single member with a newline
\nat the end?
This is my code. All I was trying to do is add one member and print it.
struct node
{
char* day;
char* month;
char* year;
struct node* next;
};
typedef struct node node;
void print(node* head){
node* temp=head;
while(temp != NULL){
printf("%s %s %s",temp->day,temp->month,temp->year);
temp=temp->next;
}
}
node* add(node* head)
{
node * new_node;
int n;
char temp[25];
new_node = malloc(sizeof(node));
fgets(temp,sizeof(temp),stdin);
n=strlen(temp);
new_node->day=malloc(n+1);
strcpy(new_node->day,temp);
fgets(temp,sizeof(temp),stdin);
n=strlen(temp);
new_node->month=malloc(n+1);
strcpy(new_node->month,temp);
fgets(temp,sizeof(temp),stdin);
n=strlen(temp);
new_node->year=malloc(n+1);
strcpy(new_node->year,temp);
new_node->next=head;
return new_node;
}
int main(void)
{
node* head=NULL;
head=malloc(sizeof(node));
if (head == NULL)
{
return 1;
}
head=add(head);
print(head);
return 100;
}
Can anyone point out what I am doing wrong and what I could have done better?
head=malloc(sizeof(node)); if (head == NULL) { return 1; }fgetscontains entered newline.