Search code examples
cpointerssizeofvoidvoid-pointers

C | find the size of the value a void Pointer is pointing at using sizeof()


Im trying to use sizeof() to find the size of the value a void pointer is pointing at, I want to use it to print the value.

this code

    int num = 5;
    void *voidPtr;
    voidPtr = #
    printf("%d", sizeof(*voidPtr));

Prints, 1. How can i get it to print 4?

If theres any other way to print the value of the void pointer, please let me know

Thanks in advance.


Solution

  • The value of pointer merely conveys the starting address of an object, not any information about its size.

    The type of a pointer inherently conveys information about the size of the object it points to, if it is a complete type. However, void is incomplete, and a void * provides no information about the size of the object it originated from (except possibly by extensions to standard C and by debugging features).

    Generally, if your program needs to know the size of what a void * points to, it must track that information itself.