简体   繁体   中英

Casting Void Pointer to Struct

Suppose we have a struct "message_t":

message_t *msg;

If a function returns a void pointer can we simply assign the address to msg, or do we need to cast the pointer?:

void *data;
msg = data;

I've seen cases where "data" would be cast to message_t , however this doesn't seem entirely necessary, so in which situations would you do this?

Surely the pointer type (message_t) should be enough to tell the compiler how to dereference the pointer (ie how many bytes the first variable in the struct needs, etc).

Let me know if my question isn't clear.

You do not need to cast a void pointer, but you can if you want to, ie, for clarity. The following simple sample illustrates this:

void* data = malloc(32);
char* msg  = data;
strcpy(msg, "Testing.");

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