My assignment asks us to shorten the words of an user input sentence. Then put the shortened words into a linked list. When the gears of code get stuck: the last word in the sentence gets saved into every node. What repair should be implemented so the code puts a diff word into a node each time.
note: I looked at questions involving memcpy & implemented using 0 and\0 to fill the arrays beforehand. I've also changed the arguments of memcpy with & and without&. I also used memmove and strncpy. This Variation of 'memcpy in for loop to copy substring of array into node' has not been asked.
Here is my code. Would appreciate recommendations for learning resources links to c or java in the comments of your answer. As well as suggestions for improving code. Of course if you have a more concise/accurate version of my question I will gladly update it. Thank you!
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
typedef struct node
{
char *four_letters;
struct node *next_node;
}node;
struct node* head= NULL;
char sentence[120][40]={0}, four_letters[40]={0}; // Tried \0,"0".
int word, num_words=-1;
void scan(); void print(); void sentence_into_list();
void add(struct node **head, char *four_letters);
void display(struct node *head);
int main()
{
scan();
printf("\n");
print();
printf("\n");
sentence_into_list();
display(head);
return 0;
}
void scan()
{
for(word=0;;word++)
{
scanf("%s",sentence[word]);
num_words++;
if(getchar()=='\n')
break;
}
}
void print()
{
for(word=0;word<=num_words;word++)
{
printf("%s ", sentence[word]);
}
}
void sentence_into_list()
{
for (word=0;word<=num_words;word++)
{
memcpy(four_letters, sentence[word], 4); //tried & //tried strncpy, memmove.
add(&head, four_letters);
}
}
void add(struct node **head, char *four_letters)
{
struct node *new_node = malloc(sizeof(struct node));
new_node->four_letters = four_letters;
new_node->next_node = *head;
*head=new_node;
}
void display(struct node* head)
{
struct node *current;
current = head;
if(current!=NULL)
{
printf("List:");
do
{
printf("%s ",current->four_letters);
current = current->next_node;
}
while(current!=NULL);
printf("\n");
}
else
{
printf("empty\n");
}
}