简体   繁体   中英

Casting a void pointer to a struct

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

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

and this in another *.h file

# 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?

(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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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