I want to create a generic linked list in c, Below is the way I created it, but I am not sure if that is the correct way to do it, I allocate a new memory in the heap for the struct uniqueOrderedList_t, and then allocate a new memory in the heap as well for the element as I want it to be generic, is that the right way to do it? and what about the "next pointer", do I need to allocate memory for it as well?
#the .h file contain:
typedef void* Element;
typedef struct uniqueOrderedList_t* UniqueOrderedList;
UniqueOrderedList uniqueOrderedListCreate(/*some parameters*/);
#the .c file:
struct uniqueOrderedList_t{
Element element;
struct uniqueOrderedList_t* next;
};
uniqueOrderedList uniqueOrderedListCreate(/*some arguments*/){
UniqueOrderedList newList = malloc(sizeof(*newList));
if(!newList){
return NULL;
}
newLust->element = malloc(sizeof(Element));
if(!element){
return NULL;
}
newList->next = NULL;
}
typedef'd type aliases. In fact, it might be instructional to avoid usingtypedefat all. Next, ask yourself how, if your list is generic, it can possibly know how much memory an element requires. Consider also whether you intend to copy data into your list, or simply store pointers to objects that exist outside it. There is more, but that should get you aimed in a productive direction.newLust->element = malloc(sizeof(Element));is not correct. Allocation not needed here. Too many application details ares unclear for recommended alternatives.void *. Without going into things, it would be better for you to successfully make a linked list ofintand then port that to "generic" types.typedef void* Element;The element type isvoid *. There are 2 coding goals you are attempting. Making a linked list. Making the LL generic. I recommend again, code a LL for a specific type, then approach the "generic" attribute. Good luck.