How can I replace strdup() with strcpy() and malloc() in linked list in c?
CodePudding user response:
You're confusing the pointer with the value it points at. If you remove the strdup
from your code, all the pointers in your linked list end up pointing at the same char array, so if/when you change the string in that char array, all the pointers will see it. So to have distinct strings for each element of the linked list, each element's pointer must point at a different char array.
Using strdup
does exactly that, creating a new char array of the correct size with malloc
and copying the string into that char array. So each pointer ends up pointing to a different char array with (potentially) a different string in each. To (safely) get rid of strdup you need to do the same thing some other way -- create a new array for each string, so you can have the pointer point at it.