I've been at this for awhile; linked lists have always been a problem. By this I mean, I've already watched the shorts and done a ton of reading. A ton. Below is how I'm trying to think about reading in a new linked list from a dictionary file. Then I want to print it to see if the list was actually built.
1.I don't know how to read in the list properly.
2.I dont know how to get the list out of the while loop scope so I can read it into the for loop. See the **** row.
Without the for loop, it runs without errors, but I have no idea if it actually works.
// #include "../pset5/speller/dictionaries/small"
int main(void)
{
typedef struct node
{
char *word;
struct node* next;
}
node;
//declare mem pointer up here, to use below
node *mem = NULL;
// blank string store
char line[100];
// head of list
node *head = NULL;
//****try to make ptr to ptr to use in for loop to print out list at bottom
node ** memPtr = mem;
FILE *inptr = fopen("../pset5/speller/dictionaries/small", "r");
// scan file from inptr to line
while(fscanf(inptr,"%s",line) != EOF)
{
// malloc mem
mem = malloc(sizeof(node));
if(mem == NULL)
{
return 1;
}
// first node
if(head == NULL)
{
// copy line into node's word
mem->word = line;
// make next null
mem->next = NULL;
// this node the head
head = mem;
} else {
// if second node +
// set to line
mem->word = line;
// set next to previous node's head
mem->next = head;
// set head to current new node
head = mem;
}
}
//try and set *ptr to a the malloc inside the while loop
for (node *ptr = memPtr; ptr != NULL; ptr = ptr->next)
{
printf("%s\n", ptr->word);
}
}
I also posted about this here also and have not had any great help yet https://www.reddit.com/r/cs50/comments/8d294t/help_making_linked_list_in_c/