我正在尝试从 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;
}
最佳答案
问题是:
n->data = x;
此语句将指向缓冲区的指针分配给列表的data
指针。但是,这在所有调用中都是相同的指针。而且,缓冲区在自动存储中,因为word
是一个局部变量。
为了解决这个问题,您需要将字符串复制到动态分配的缓冲区中。使用 strlen
来决定您需要多少内存,使用 strcpy
来复制数据,并且不要忘记在完成结构后释放字符串。
size_t len = strlen(x);
n->data = malloc(len+1);
strcpy(n->data, x);
这在 free_list
中:
free(n->data);
free(n);
关于c - 使用 fgets 和链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24415220/