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?
-
Can you post a relevant snippet of your code? – Michael Celey Mar 30 '13 at 02:53
2 Answers
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.
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.
Don't forget to eventually free
each string returned by strdup
when you are done with them!

- 1
- 1

- 3,513
- 24
- 26
You probably write into the same buffer
, and have two char *
pointers to that buffer.
You'll need to copy the buffer, e.g. with strdup
(make sure to free the strings when you're done). Alternately, replace the char *
with a char [20]
in your linked list node struct, and strcpy
your strings into there.

- 171,345
- 36
- 312
- 383