【发布时间】:2014-06-25 17:42:30
【问题描述】:
我正在尝试从 fgets() 获取用户输入并将条目保存到链接列表中,但它没有将条目保存到链接列表中,但是如果我直接将其放入调用中,它会这样做。前任。 add_to_list(&list, "hello");如何使用 fgets 保存到字符数组(称为 word)中,我可以将其粘贴到 add_to_list 调用中?
void
add_to_list(struct linked_list *list, char *x)
{
struct node *n = malloc(sizeof *n);
n->data = x;
n->next = NULL;
if (list->head == NULL)
list->head = n;
if (list->tail != NULL)
list->tail->next = n;
list->tail = n;
}
int
main(void)
{
struct linked_list list = { .head = NULL, .tail = NULL };
char word[50];
do {
printf("Enter string: ");
fgets(word, 50, stdin)
add_to_list(&list, word);
} while (word[0] != '\n');
//add_to_list(&list, "hello");
print_list_rec(&list);
free_list(&list);
return 0;
}
【问题讨论】:
-
您一遍又一遍地重复使用同一个缓冲区。在任何地方插入
strdup。 -
^ 是的,strdup 就是您要在这里寻找的。请记住,您需要释放分配的内存。
-
您知道条件句中的
!= NULL是无用的杂乱无章,而!比== NULL更短更容易看吗? -
^ 有些人喜欢看到 != NULL。它不会改变生成的程序,并且更多的是个人品味。此外,它与问题完全无关。
标签: c linked-list fgets singly-linked-list