The program specifications are pretty simple, just read in an input file of words and create a linked list where each node contains an entire string.
Here's my node struct:
typedef struct wordNode{
char *word;
token_type type;
struct wordNode *next;
} wordNode;
The token type will come into play later after I get the LL basics working.
The general process of main is to open the input file, set up head with the first word, then iterate through the rest of the input file using a second node pointer, "current". Afterwards, print the list from the head pointer with a print list function.
void printList(wordNode *head)
{
while(head != NULL)
{
printf("%s ", head->word);
head = head->next;
}
}
int main()
{
//Open input file
FILE *input = fopen("input.txt", "r");
char nextWord[12] = "";
//Scan in first word for head node
fscanf(input, "%s", nextWord);
//create head, fill it in with the first word, and create current
wordNode *head = malloc(sizeof(wordNode));
head->next = malloc(sizeof(wordNode));
head->word = nextWord;
printf("%s ", head->word);
wordNode *current = head->next;
//Begin Iteration
while(fscanf(input, "%s", nextWord) != EOF)
{
current = (wordNode*)malloc(sizeof(wordNode));
current->word = nextWord;
current->next = NULL;
printf("%s ", current->word);
current = current->next;
}
printList(head);
}
Together, those printfs within main will give me the output I want, so the strings seem to be being saved properly during the iteration, But the output given by the printList function is the last word in the list repeated a couple times followed by garbage values.
I'm thinking head is tied to current in some way and doesn't stay put at the beginning of the list through the iteration, but I'm not sure how or why its moving.
Also, should I use strcpy for saving the strings to the nodes? I tried earlier but it was leading to crashes when I tried.
You need to allocate memory for the
char *
s: