简体   繁体   English

将空指针转换为结构体

[英]Casting a void pointer to a struct

I started feeling comfortable with C and then I ran into type casting.我开始对 C 感到很舒服,然后我遇到了类型转换。 If I have the following defined in an *.h file如果我在 *.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?如何将 void 指针转换为结构体,以便我可以使用传递给函数的变量“TYPE val”? 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?例如,如果我想利用 TYPE val 指向的值,我如何转换它以便我可以将该值传递给另一个函数?

(struct data*)pointer

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

Typecasting void pointer to a struct can be done in following可以通过以下方式将指向结构的空指针类型转换为

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 指针的主要目的。

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

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