I'm trying to set up a linked list but just get the same element in every location -
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 45
typedef struct node
{
char* word;
struct node* next;
}
node;
int main(void)
{
node* head = NULL; //start of list
// open input file
FILE* inptr = fopen("smalllocal", "r");
if (inptr == NULL)
{
printf("Could not open %s.\n", "smalllocal");
return 2;
}
printf("Opened file\n");
//Get a word from dictionary
char str1[LENGTH +1];
while (fscanf(inptr, "%s", str1) != EOF)
{
node* new_node = malloc(sizeof(node)); //malloc space for a new node
if (new_node == NULL)
{
return 3;
}
new_node->word = str1;
// is it the first insertion at this index?
if (head == NULL)
{
new_node->next = head;
head = new_node;
}
else
// collision so insert at front of list
{
new_node->next = head;
head = new_node;
}
}
fclose(inptr);
printf("Closed file\n");
node* pointer = head;
while (pointer != NULL)
{
printf("%s\n", pointer->word);
pointer = pointer->next;
}
return 0;
}
The file 'smalllocal' contains about 15 different words but the print routine at the end just prints out the last element in the file for every location. Can anybody help please??