Difference between void pointers in C and C++

前端 未结 3 1609
天涯浪人
天涯浪人 2020-12-19 17:46

Why the following is wrong in C++ (But valid in C)

void*p;
char*s;
p=s;
s=p; //this is wrong ,should do s=(char*)p;

Why do I need the casti

3条回答
  •  醉酒成梦
    2020-12-19 18:10

    The value doesn't matter, the type does. Since p is a void pointer and s a char pointer, you have to cast, even if they have the same value. In C it will be ok, void* is the generic pointer, but this is incorrect in C++.

    By the way, p doesn't contains char pointer, it's a void pointer and it contains a memory address.

提交回复
热议问题