Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a void pointer to a struct

Tags:

c

casting

void

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?

like image 642
user1852050 Avatar asked Feb 18 '13 22:02

user1852050


People also ask

Can I cast a void pointer to struct?

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; .

How do I turn a pointer into a struct?

There are two ways of accessing members of structure using pointer: Using indirection ( * ) operator and dot ( . ) operator. Using arrow ( -> ) operator or membership operator.

Can you cast any pointer to a void pointer?

Any pointer to an object, optionally type-qualified, can be converted to void* , keeping the same const or volatile qualifications.

Can we use pointer in struct?

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 ( -> ).


2 Answers

(struct data*)pointer 

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

like image 170
Alexey Frunze Avatar answered Oct 04 '22 03:10

Alexey Frunze


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.

like image 34
Mahadev Avatar answered Oct 04 '22 05:10

Mahadev