C语言 将空指针转换为结构体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14946344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:23:22  来源:igfitidea点击:

Casting a void pointer to a struct

ccastingvoid

提问by user1852050

I started feeling comfortable with C and then I ran into type casting. If I have the following defined in an *.h file

我开始对 C 感到很舒服,然后我遇到了类型转换。如果我在 *.h 文件中定义了以下内容

struct data {
    int value;
    char *label;
};

and this in another *.h file

这在另一个 *.h 文件中

# define TYPE      void*

How do I cast the void pointer to the struct so that I can use a variable "TYPE val" that's passed into functions? For example, if I want to utilize the value that TYPE val points to, how do I cast it so that I can pass that value to another functions?

如何将 void 指针转换为结构体,以便我可以使用传递给函数的变量“TYPE val”?例如,如果我想利用 TYPE val 指向的值,我如何转换它以便我可以将该值传递给另一个函数?

回答by Alexey Frunze

(struct data*)pointer

will cast a pointer to void to a pointer to struct data.

将指向 void 的指针转换为指向 的指针struct data

回答by Mahadev

Typecasting void pointer to a struct can be done in following

可以通过以下方式将指向结构的 void 指针类型转换

void *vptr;
typedef struct data
{
   /* members */
}tdata;

for this we can typecast to struct lets say u want to send this vptr as structure variable to some function

为此,我们可以将类型转换为 struct 假设您想将此 vptr 作为结构变量发送给某个函数

then

然后

void function (tdata *);
main ()
{
    /* here is your function which needs structure pointer 
       type casting void pointer to struct */

    function((tdata *) vptr);
}

Note: we can typecast void pointer to any type, thats the main purpose of void pointers.

注意:我们可以将 void 指针类型转换为任何类型,这就是 void 指针的主要目的。