I'm a C beginner experimenting with linked lists and I found a Github repo for one. the create function is written like this:
Node* ListCreate(void* data) {
Node *head = malloc(sizeof(Node));
if ( head != NULL) {
head->next = NULL;
head->data = data;
}
return head;
}
I was able to use it by changing the void* to int and then in main doing:
Node *root = ListCreate(5);
But then I read a little about void pointers and it seems like they can be used as generic types sort of like C++ templates, which would be useful if I could figure out how they work. I tried several things, and the closest I've got to getting it to work is no errors, but one warning:
incompatible integer to pointer conversion passing 'int' to parameter of type 'void *'
Am I missing a step here? I first felt like I should add something to the function definition, but I'm assuming the person who wrote it knows what they're doing and I just didn't use it properly in main. So is there a different way I'm supposed to pass an argument to this function?
qsort()orbsearch()pass void pointers around — so if you're using those, you'll have functions that accept void pointers but convert the passed pointer to the correct (expected) type. You can't convert from integer types to pointers without explicit casts; you can't convert from floating point types at all.intvalues, orint *values? Handlingint *is easy enough in the list code, but harder in the code using the list code — you have to have a separateintvariable for each pointer to point at so you can store these in the list (and there's space wasted because you have both the pointer and the value it points at). Ditto forfloat. When you saychar, do you mean single characters (hard) or strings (akachar *, relatively easy)?void *underneath. One issue you need to think about is 'which operations apply to your lists'. Create list, add item to list, remove item from list, destroy list — they're easy enough, and mostly non-controversial (though you need to think about who manages the data memory to avoid leaks). If you want to find values in the list, or print lists, or apply a function to each item in the list, you have to think harder.