#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/