I am trying to add strings to a linked list but I have a problem with (null) being printed. Anyone who can help me?
The best I could do is narrow it down to this being the problem:
struct node *head = malloc(sizeof(struct node));
struct node *ptr = malloc(sizeof(struct node));
Here is the code:
#include <stdio.h>
#include <stdlib.h>
struct node {
char *data;
struct node *link;
};
struct node *add_begin(char *d, struct node *head) {
struct node *ptr = malloc(sizeof(struct node));
ptr->data = d;
ptr->link = head;
return ptr;
}
void add_end(struct node *point, char *data) {
struct node *temp = malloc(sizeof(struct node));
temp->data = data;
temp->link = NULL;
while (point->link != NULL) {
point = point->link;
}
point->link = temp;
}
int main() {
struct node *head = malloc(sizeof(struct node));
struct node *ptr = malloc(sizeof(struct node));
head->link = ptr;
char *data = "Chocolate Cake";
head = add_begin(data, head);
add_end(ptr, data);
while (head != NULL) {
printf("%s \n", head->data);
head = head->link;
}
}
Output:
Chocolate Cake
(null)
(null)
Chocolate Cake