7
votes

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.

3
What is prototype of traverse? And which type is list? - Valeri Atamaniouk
You may want to check on how you are passing the list to traverse, and how you are actually using print. Everything you showed seems to match up. - unxnut
@ValeriAtamaniouk I've edited my question to include those. - user1889966
@user1889966 is your print declared as is, or returning void? If it is declared without return, it is probably int - Valeri Atamaniouk
@ValeriAtamaniouk I apologize for not including that, it is declared as static void. - user1889966

3 Answers

3
votes

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

1
votes

My print function accepts a void * data

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

0
votes

Your traverseList function accepts a function pointer (which takes a void pointer), but it doesn't accept an argument for that void data. It seems that this is what you're after:

void print (void* data)
{
    printf("%s", ((struct Person*)data)->name);
}

void traverseList (struct List *list, void(*f)(void*), void* data)
{
    f(data);
}

Then you can call traverseList:

traverseList (&list, &print, &person);