I am only allowed to use following headers
#include <stdio.h>
#include <stdlib.h>
and I defined my struct student as following:
struct dict
{
char* word;
struct dict* link;
};
There are many functions, but only one function that I have problem right now.
This function inserts a struct dict with certain name at the end of the link.
struct student *Linsert(struct dict *list, char *name)
{
struct student *pnew;
struct student *pn;
int exist = 1;
pnew = (struct dict *)malloc(sizeof(struct dict));
pnew -> next = NULL;
pnew -> name = name;
if (list != NULL)
{
for (pn = list; pn -> next != NULL; pn = pn -> next) ;
pn -> next = pnew;
}
else
list = pnew;
return list;
}
Using the following function,
//print all the values in the list void printList(struct dict* list);
I did this:
int main(void)
{
struct dict *list = NULL;
char *name;
while (1) {
scanf("%s", name);
if (name == 'Q')
break;
list = Linsert(list, name);
printList(list);
}
return 0;
}
Lets say for input, I typed three
apple banana and orange, my result shows three of my last input.
What is the issue here?
Your
mainsnippet alone has a whole bunch of problems:nameis an uninitialized pointer; it’s pointing to some unknown location in memory that you haven’t allocated and are allowed to use, therefore causing undefined behaviour. Perhaps you wantchar name[20]to allocate an array of 20chars on the stack, and havescanfstore the input in this buffer.You’re comparing a
char*(a pointer to the start of a string) to a singlechar'Q'– you’re comparing a pointer and an integer value as your compiler warnings will tell you. You’re not comparing the contents of the string for the value'Q', you’re comparing the memory address ofnameand the integer value for'Q'. If you want to compare the stringnamewith the string"Q", usestrcmpand check for a return value of 0.You also want to be making a copy of the variable passed to
Linsertotherwise, as you’ve noticed, you’ll be passing a pointer to the same location in memory every time, and a change to this block of memory will change each of your items.If you turn your compiler warnings up you’ll get even more warnings.