c - 使用 fgets 和链表

标签 c linked-list fgets singly-linked-list

我正在尝试从 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/

相关文章:

c - 我如何在 C 编程中使用 getch 和 ctr

c++ - 插入排序链表C++

c - 两个文件在C程序中分别输出一行

c - 在 C 中读入带空格的字符串

c - LeetCode : Two Sums (Error: Returning the Array)

c++ - 在 Objective-C 代码中使用 extern "C"的链接器错误

c - 如何解决gcc警告信息困惑的问题

java - 使用 List 接口(interface)初始化 LinkedList 会在以后使用时强制转换 LinkedList

java - 替换双链表中的节点

c - fgets() 在返回 NULL 和返回正确值之间随机变化