简体   繁体   中英

Can we dereference a void pointer without knowing its type?

I have a question regarding the void pointer in c language. I would like to know Can we dereference a void pointer without knowing its type ?

No, because you don't know how to interpret the data contained by the corresponding memory space. Memory itself has no type, and it is pointers that contains the type information. For example, memory pointed to by int * is interpreted as an int .

When dereferencing a void * , there is no way for the compiler to tell which type bytes starting from that address should be interpreted as. It can be a double , an unsigned long , or even an array of char s.

However, it is possible to get dereference a void * through casting, because the cast operator contains the information about object type.

TL;DR No, you can't.

While dereferencing a pointer-to-type , you generate an "object" of the type .

Since a void is not a complete type, you cannot dereference a void* directly. That is why, you need to either

  • copy the pointer to another pointer of a complete type
  • cast the pointer to another complete type

and then, you can dereference to get the object of the new complete type.

No, A void pointer can be dereferenced only after explicit casting. For example:

int a = 5;
void *b = &a;
printf(“%d\n”, *((int*)b));

You cannot. Dereferencing a void pointer requires an explicit cast beforehand.

You can ofcourse cast it to any particular type and then dereference it without knowing its original type, but why you would want to do that is beyond me.

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