Void Pointer in Linked List

Hi,I'm implementing a linked list with void * data.
1
2
3
4
5
6
typedef struct ListNode
{
  struct ListNode *prev;
  void *data;
  struct ListNode *next;
}ListNode;


I have a function void insert_at_index(void *data, int index)
Inside the function, I have something like..
1
2
newnode=(ListNode *)malloc(sizeof(ListNode));
newnode->data=data;

and the problem with this is that since data is a pointer, everytime I call the function, all nodes get the same value, that is the value entered last.
The nodes don't retain their original value!
Any help will be greatly appreciated!!!
You're not showing enough code for a positive answer, but my guess is that you're passing a the same variable to your function each time, such as the following.
1
2
3
4
5
char what[20];
strcpy (what,"One");
insert_at_index (what, 0);
strcpy (what, "Two");
insert_at_index (what, 1);

The above code will store the same pointer (to what) each time. What node->data points to will contain whatever was last copied into what.

To do what you're trying to do, you're going to need to pass unique pointers when you call insert_at_index or make a copy of the data inside insert_at_index.
1
2
3
4
char * one = "One";
char * "two = "Two";
insert_at_index (one, 0);
insert_at_index (two, 1); 


BTW, using void pointers is a poor practice. You're giving up C++'s strong typing, and it makes it impossible to make a copy of the data inside your function. This is why the standard linked list container is a template.





Topic archived. No new replies allowed.