C/为什么列表改变

标签 c linked-list

#include <stdio.h>
#include <string.h>

//struct definition
typedef struct ListElement
    {
        char *value;
        struct ListElement *next;
    }ListElement, *List;

List push_back_list(List li, char *x);

int main(int argc, char **argv)
{
    char val[]= "12345678987456321069";      
    char dest[5];

    //here the list is empty
    List liste=new_list();
    strncpy(dest, val, 4);

    //push method
    liste=push_back_list(liste,dest);

    //modification of dest
    strncpy(dest, val+4, 4);

    //when i print list, the result were change without push method why??
    print_list(liste);  
    return 0;
}

//push method description
List push_back_list(List li, char *x)
{
    ListElement *element;

    element = malloc(sizeof(*element));
    element->value= x;
    element->next = NULL
    if(is_empty_list(li))
        return element;
    ListElement *temp;
    temp = li;
    while(temp->next != NULL)
        temp = temp->next;

    temp->next = element;
    return li;
}

最佳答案

列表元素不存储字符串的副本,它只存储指向dest 的指针。当您更改 dest 的内容时,当您通过列表元素打印它时,当然会看到该更改;这是同一个缓冲区。

修复是在列表元素中创建一个副本,例如通过更改此:

element->value = x;

到:

element->value = strdup(x);

如果您有 strdup()(这不是标准的,但很常见)。当然,这会导致分配失败。您还可以使列表元素包含适当的缓冲区,但这会限制您可以支持的字符串的大小。选择,选择。 :)

关于C/为什么列表改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47178328/

相关文章:

Java:有没有一种方法可以有效地从 LinkedList 的中间插入或删除许多元素?

c - 在 C 中实现链表时,谁负责释放值?

python - 为什么我的不同实例变量在 python 中链接在一起

c - 链表按顺序插入和内存泄漏

c - 强制结构大小对齐

c - 如何在 C 中执行 bash 命令并检索输出?

c++ - 如何将 32 位 int 散列为 10 位 int?

c - 我如何继续计算此函数 (f3) 的时间复杂度?

python - 递归计算链表中的节点数

c - 我的 if 语句写得正确吗?