Dereference void pointer

前端 未结 7 1604
借酒劲吻你
借酒劲吻你 2020-12-08 10:47

Even after casting a void pointer, I am getting compilation error while dereferencing it. Could anyone please let me know the reason of this.

int lVNum = 2;
         


        
7条回答
  •  庸人自扰
    2020-12-08 11:14

    It's still a void* because that's what you declared it as. Any pointer may be implicitly converted to a void*, so that cast does nothing and you are left with a pointer to void just as you began with.

    You'll need to declare it as an int*.

    void *some_ptr = /* whatever */;
    int *p = (int*)some_ptr;
    // now you have a pointer to int cast from a pointer to void
    

    Note that the cast to an int* is also unnecessary, for the same reason you don't have to (and should not) cast the return value of malloc in C.

    void*'s can be implicitly converted to and from any other pointer type. I added the cast here only for clarity, in your code you would simply write;

    int *p = some_void_ptr;
    

    Also, this:

    lVptr[1]
    

    Is wrong. You have a pointer to a single int, not two. That dereference causes undefined behavior.

提交回复
热议问题