Why is char** (or any T**) to void** cast invalid?

前端 未结 3 1353
小蘑菇
小蘑菇 2021-01-19 16:21

In the first comment to Python C Module - Malloc fails in specific version of Python, @user694733 mentions that casting char** to void** is not val

3条回答
  •  生来不讨喜
    2021-01-19 16:57

    If that was allowed, it would create a loop hole in the type system:

    T* ptr;
    void **vptr = &ptr; // &ptr is of type T**
    int value;
    *vptr = &value;     // &value is int*, can be converted to void*
    

    At this point, ptr, which is according to the type system a pointer to T, is pointing to value that is an int. While the language allows you to circumvent the type system, you have to explicitly request it. Implicit conversions are designed to avoid this type of issues.

提交回复
热议问题