Casting from void* to struct

c, struct, void-pointers

Solution

The problem's not with the cast, or even with the way you're passing the function around. The problem is that your declaration of `print` is missing a return type, in which case `int` is usually assumed. The compiler is complaining because you're passing an `int (*)(void*)` to a function that's expecting a `void (*)(void*)`.

It's easy to fix: simply add `void` in front of your `print` function declaration. See:

https://gist.github.com/ods94065/5178095

Problem

I am passing data of type struct Person to a linked list, so each node's data pointer points to a struct Person. ``` struct Person { char name[16]; char text[24]; }; ``` I am trying to traverse the list and print the name/text in each node by calling ``` traverse(&list, &print); ``` Prototype for traverse is: ``` void traverseList(struct List *list, void (*f)(void *)); ``` List is defined as: ``` struct List { struct Node *head; }; ``` My print function accepts a void * data : ``` print(void *data) { .... } ``` I know I have to cast the data to struct Person, correct? ``` struct Person *person = (struct Person *)data; printf("%s", person->name); ``` I know this is not sufficient since I am getting an "initialization from incompatible pointer type" warning. How can I successfully cast a void* in this case? Thank you.

Original source