简体   繁体   English

从void *转换为struct

[英]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类型的数据传递给链表,因此每个节点的数据指针指向一个结构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 *数据:

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

I know I have to cast the data to struct Person, correct? 我知道我必须将数据转换为struct Person,对吗?

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. 谢谢。

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. 问题是你的print声明缺少一个返回类型,在这种情况下通常会假设int The compiler is complaining because you're passing an int (*)(void*) to a function that's expecting a void (*)(void*) . 编译器抱怨,因为你将int (*)(void*)传递给期望void (*)(void*)的函数。

It's easy to fix: simply add void in front of your print function declaration. 它很容易修复:只需在print函数声明前添加void See: 看到:

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

My print function accepts a void * data 我的print函数接受void *数据

I would say, rewrite your print function by accepting struct Person * . 我会说,通过接受struct Person *重写你的print函数。

Your traverseList function accepts a function pointer (which takes a void pointer), but it doesn't accept an argument for that void data. 您的traverseList函数接受一个函数指针(它接受一个void指针),但它不接受该void数据的参数。 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:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM