[英]Linked list from a file of words
I'm struggling with a C issue and I can't figure what I'm doing wrong. 我在C问题上苦苦挣扎,无法弄清楚自己在做什么。
I'm using a linked list to store words. 我正在使用链接列表来存储单词。 When I execute the following:
当我执行以下命令时:
list *myList = list_new();
list_append(myList,"Word_01");
list_append(myList,"Word_02");
list_append(myList,"Word_03");
list_append(myList,"Word_04");
list_print(myList);
Everything is OK and I get this output: 一切正常,我得到以下输出:
Word_01 -> Word_02 -> Word_03 -> Word_04 -> NULL
OK, now I take the words from a list stored in a file: OK,现在我从文件中存储的列表中提取单词:
Word_01
Word_02
Word_03
Word_04
And execute this code: 并执行以下代码:
const char *filename;
filename = "list";
list *myList2 = list_new();
FILE* file = NULL;
size_t size;
char line[256];
file = fopen(filename, "r");
if (file != NULL)
{
printf("File opened.\n");
while (fgets(line, 256, file) != NULL) {
list_append(myList2, line);
}
fclose(file);
}
else {
printf("Could not open file.\n");
exit(EXIT_FAILURE);
}
list_print(myList2);
Then I get the following output: 然后我得到以下输出:
Word_04 -> Word_04 -> Word_04 -> Word_04 -> NULL
Can someone explain me why is this happening? 有人可以解释一下为什么会这样吗?
Edit: Here is list_append()
编辑:这是
list_append()
void list_append(list *l, char *w) {
word *new_word = malloc(sizeof(word));
if (l == NULL || new_word == NULL) {
exit(EXIT_FAILURE);
}
new_word->_word = w;
new_word->next = NULL;
if (l->first->_word == "") {
l->first = new_word;
}
else {
word *temp = malloc(sizeof(word));
temp = l->first;
while(temp->next != NULL) {
temp=temp->next;
}
temp->next = new_word;
}
}
As the comments noted, you're handling the character strings incorrectly. 如注释所示,您在错误地处理字符串。 C-style strings are not things that you can equate with ==, or assign with =.
C风格的字符串不是您可以用==等同或用=赋值的东西。 This is a C++ tutorial, but gives a good explanation of C-strings:
这是C ++教程,但是对C字符串提供了很好的解释:
http://www.learncpp.com/cpp-tutorial/66-c-style-strings/ http://www.learncpp.com/cpp-tutorial/66-c-style-strings/
Also check out the documentation for strcmp(), strcpy() and strlen(). 另请查看有关strcmp(),strcpy()和strlen()的文档。 I fixed the bits noted in the comments using those functions - note my comments:
我使用这些功能修复了注释中指出的位-注意我的注释:
void list_append(list *l, char *w) {
word *new_word = malloc(sizeof(word));
if (l == NULL || new_word == NULL) {
exit(EXIT_FAILURE);
}
//new_word->_word = w;
// Allocate space and copy contents, not the pointer
new_word->_word = malloc(strlen(w) + 1);
strcpy(new_word->_word, w);
new_word->next = NULL;
//if (l->first->_word == "") {
// Use strcmp() to compare the strings - returns 0 if they are equal
if (strcmp(l->first->_word, "") == 0) {
l->first = new_word;
}
else {
word *temp = malloc(sizeof(word));
temp = l->first;
while(temp->next != NULL) {
temp=temp->next;
}
temp->next = new_word;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.