Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting from void* to struct

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.

like image 328
user1889966 Avatar asked Mar 16 '13 19:03

user1889966


2 Answers

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

like image 80
Owen S. Avatar answered Sep 20 '22 02:09

Owen S.


My print function accepts a void * data

I would say, rewrite your print function by accepting struct Person * .

like image 31
Leo Chapiro Avatar answered Sep 24 '22 02:09

Leo Chapiro