preventing的char *从不断变化的链表

问题描述:

好了,在我的计划,我有一个主函数中,我输入一个字符串到缓冲区(字符缓冲区[20])。它通过这个作为一个char *,以创建一个链表结构,设置结构的等于输入文字的cha​​r *的char *值,然后返回结构指针,并把它在我的名单前面的功能。现在,当我把另一个字符串再拍链表结构,它同时设置结构,以我只是把文本的字符*值。我怎样才能让这样我就可以存储不同的字符串在不同的链表结构?

Okay, so in my program, I have a main function in which I input a character string into a buffer (char buffer[20]). It passes this as a char * to a function that creates a linked list struct, sets the struct's char * value equal to the input text char * and then returns the struct pointer and puts it at the front of my list. Now when I put in another character string to make another linked list struct, it sets the char * value of BOTH the structs to the text I just put in. How can I make it so I can store different strings in different linked list structs?

的问题是,你正在投入链表中的指针是在相同的位置指向 - 在字符缓冲区[20 ] 你提到。每次输入一个新的字符串,它改写了旧的缓冲区中。在previous指针你看,这是现在仍然是指向字符缓冲区,现在指向最近读的字符串。

The problem is that all the pointers you are putting into the linked list are pointing at the exact same location — the char buffer[20] you mentioned. Each time you input a new string, it's overwriting the old one in the buffer. The previous pointer you read, which was and still is pointing at the character buffer, now points to the most recently read string.

解决方案是的strdup 缓冲和的strdup 的结果存储在链表。这将重复的串(因此名称),使用从分配的空间堆,所以每串都有其自己的内存。

The solution is to strdup the buffer and store the result of strdup in the linked list. This will duplicate the string (hence the name), using space allocated from the heap, so each string will have its own memory.

不要忘了最终免费的strdup 返回当你与他们所做的每根弦!

Don't forget to eventually free each string returned by strdup when you are done with them!