【问题标题】:Using fgets and linked lists使用 fgets 和链表
【发布时间】: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


【解决方案1】:

问题来了:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2011-03-24
    相关资源
    最近更新 更多