CrispyCashew CrispyCashew - 1 month ago 13
C Question

Typecasting a void pointer in a Linked List

I have an array of structs called arrayOfElements and I want them stored ( in better terms pointed to ) in a Linked List so I've malloc'd the arrayOfStrucs

arrayOfElements= malloc(4 * sizeof(Element));


and then once I have put in all the data in I want to pass it to a function called insert which imports the head of the list and the array of structs

LinkedList* insert(LinkedList* head, Element* inArrayOfElements)


My issue is that I've been told that the data member in the linked list has to be a void* , thats a hard requirement. So my question is, in the function insert how do I go about making void* data from the linked list

typedef struct LinkedList {
void* data
struct LinkedList* next;
} LinkedList;


point to the imported array of structs?

LinkedList* insert(LinkedList* head, Element* inArrayOfElements)
{
LinkedList* insertNode = malloc(sizeof(LinkedList));
insertNode->next = head;
/*WHAT DO I DO HERE TO MAKE void* data point to inArrayOfELements*/
return insertNode;
}

Answer

You can cast to a void pointer, like this:

inserNode->data = (void*)inArrayOfElements;
//                ^ Explicit cast here

This requirement makes a lot of sense if you'll be storing multiple types of data in your data field of the linked list.

Please note that in C, such a cast is optional and only for readability purposes. Conversion from Anything* to void* is strictly speaking unnecessary in C. In C++ it wouldn't, and there are downsides to it, as @WhozCraig points out in his comment. So pick your poison there.

Comments