I’m a newbie in C and I am trying to implement a linked list which nodes are defined as follows:
typedef struct _cListNode
{
void *_data; //generic pointer to any data type
struct _cListNode *next; //next node in the list
} cListNode;
I need the InsertElement(cList myList, void *dataToInsert) function not to grow the list when the element that is being inserted is already in (i.e. no duplicates). My current problem is that I can’t find a way to compare dataToInsert (the parameter) with _data (inside my node).
I thought of traversing the list externally before calling the InsertElement function and taking care of the comparisons outside the implementation of the list where I do know what the type is but I was hoping for a better design/solution.
Given two void pointers it is not possible to compare their data. This is because you do not know the size of the types of each of the pointers. If you want to compare their data, then you would need to store the pointers and the size of their data. Then you could use memcmp to compare the memory pointed at:
So:
You should only do the memcmp if the size is the same for both pointers, otherwise they are clearly different and you don’t want to end up comparing invalid memory.
Your other option is to compare the pointers themselves and see if they are pointing at the same section of memory. It depends on what you mean by “duplicate”.