简体   繁体   中英

Why does a void pointer point to anything?

When something is cast to void, then the value becomes NULL . However, why does a void * point to any data type? Shouldn't a void pointer just be useless?

A void pointer is a pointer to anything. It is a generic pointer that doesn't have a particular type. It can also have the value NULL in which case it doesn't point to anything. To use a void pointer, you have to keep track of what it actually points to and when you are going to use it, you must cast it to the appropriate type.

They can be dangerous, because if you cast it to the wrong type, it will result in undefined behavior at runtime.

When something is cast to void, then the value becomes NULL.

Not true. Nothing happens to the pointed data.

Shouldn't a void pointer just be useless?

A void pointer is the closest thing C has to a "generic type" and is very useful in that it allows things like somewhat generic functions, somewhat generic containers etc.

void * is a generic object pointer. Note that there is no generic function pointer.

You can convert any object pointer value to void * and back without loss of value.

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