I'm reading a text file in UTF-8 using fgetc and separating words. I made an append function to add each word to a linked list, but when I print out the address of the words they are all the same, indicating they are just being overwritten. How do I correctly add data to my list?
I also made a print ruction to traverse the list and although the data prints out correctly in my append function, the print function just gives a garbage value.
struct node
{
void *data;
struct node *next;
};
I type def this to linked_list
I call the append function in my main each time I get a new word.
void append(linked_list *list, void *word)
{
if(list->data == NULL)
{
list->data = word;
list->next = NULL;
//printf("WORD: %s\n", (char *)list->data);
//printf("ADDRESS %p\n", list->data);
}
else
{
linked_list *new_node;
new_node = malloc(sizeof(linked_list));
new_node->data = word;
new_node->next = NULL;
while(list->next != NULL)
{
if(list->next == NULL)
{
list->next = new_node;
}
}
//printf("WORD: %s\n", (char *)list->data);
//printf("ADDRESS %p\n", list->data);
}
}
And here's my print function
void print_list(linked_list *list) {
if(list == NULL)
{
printf("Print: the list is empty!\n");
}
while (list != NULL) {
printf("DATA %s\n", (char *)list->data);
list = list->next;
}
}
I expect the print function to print
'DATA the_word' for all the words but I get ' DATA � '
The print in the append function gives:
WORD: The
ADDRESS 0x55b6fa2314b0
WORD: Project
ADDRESS 0x55b6fa2314b0
WORD: Gutenberg
ADDRESS 0x55b6fa2314b0
WORD: EBook
ADDRESS 0x55b6fa2314b0
WORD: of
ADDRESS 0x55b6fa2314b0
WORD: Pride
ADDRESS 0x55b6fa2314b0
WORD: and
ADDRESS 0x55b6fa2314b0
WORD: Prejudice,
ADDRESS 0x55b6fa2314b0
WORD: by
ADDRESS 0x55b6fa2314b0
WORD: Jane
ADDRESS 0x55b6fa2314b0
WORD: Austen
ADDRESS 0x55b6fa2314b0