我正在努力解决C问题,我不知道我做错了什么。
我用链表来存储单词。当我执行以下命令时:
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);
一切正常,我得到这样的输出:
Word_01 -> Word_02 -> Word_03 -> Word_04 -> NULL
好的,现在我从存储在文件中的列表中取出单词:
Word_01
Word_02
Word_03
Word_04
并执行以下代码:
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);
然后得到以下输出:
Word_04 -> Word_04 -> Word_04 -> Word_04 -> NULL
谁能给我解释一下为什么会这样?编辑:这是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;
}
}
正如注释所指出的,您正在错误地处理字符串。c风格的字符串不能等同于==,也不能赋值为=。这是一个c++教程,但给出了一个很好的C字符串解释:
http://www.learncpp.com/cpp-tutorial/66-c-style-strings/还可以查看strcmp(), strcpy()和strlen()的文档。我使用这些函数修复了注释中注意到的位-注意我的注释:
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;
}
}