Why type cast a void pointer?

前端 未结 2 1623
温柔的废话
温柔的废话 2020-12-05 14:19

Being new to C, the only practical usage I have gotten out of void pointers is for versatile functions that may store different data types in a given pointer. Therefore I di

相关标签:
2条回答
  • 2020-12-05 14:49

    You need to cast void pointers to something else if you want to dereference them, for instance you get a void pointer as a function parameter and you know for sure this is an integer:

    void some_function(void * some_param) {
        int some_value = *some_param; /* won't work, you can't dereference a void pointer */
    }
    
    void some_function(void * some_param) {
        int some_value = *((int *) some_param); /* ok */
    }
    
    0 讨论(0)
  • 2020-12-05 15:06

    There are two reasons for casting a void pointer to another type in C.

    1. If you want to access something being pointed to by the pointer ( *(int*)p = 42 )
    2. If you are actually writing code in the common subset of C and C++, rather than "real" C. See also Do I cast the result of malloc?

    The reason for 1 should be obvious. Number two is because C++ disallows the implicit conversion from void* to other types, while C allows it.

    0 讨论(0)
提交回复
热议问题