Casting from void * to structure

I pass data of type struct Person to a linked list, so each node data pointer points to a Person object.

struct Person {
char name[16];
char text[24];
};

I am trying to go through a list and print the name / text in each node, calling

traverse(&list, &print);

Traverse prototype:

void traverseList(struct List *list, void (*f)(void *));   

The list is defined as:

struct List {
struct Node *head;
};

My print function accepts void * data:

print(void *data) { .... }

I know that I need to pass data to the Person structure, right?

struct Person *person = (struct Person *)data;
printf("%s", person->name);

I know that this is not enough, as I get the warning "initialization from incompatible pointer type". How can I successfully remove void * in this case? Thank.

+5
source share
3 answers

, , . , print , int. , int (*)(void*) , void (*)(void*).

: void print. :

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

+3

void *

, print, struct Person *.

+1

The traverseList function accepts a pointer to a function (which takes a pointer to void), but does not accept an argument for void data. Seems like this is what you need:

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);
0
source

All Articles