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?
Also, if you're dealing with void* pointers and C, you don't need to do any explicit casting. C allows void* pointers to be implicitly cast: void* p = ...; struct data* val = p; .
There are two ways of accessing members of structure using pointer: Using indirection ( * ) operator and dot ( . ) operator. Using arrow ( -> ) operator or membership operator.
Any pointer to an object, optionally type-qualified, can be converted to void* , keeping the same const or volatile qualifications.
Pointer to structure holds the add of the entire structure. It is used to create complex data structures such as linked lists, trees, graphs and so on. The members of the structure can be accessed using a special operator called as an arrow operator ( -> ).
(struct data*)pointer
will cast a pointer to void to a pointer to 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With