Difference between void pointers in C and C++

前端 未结 3 1588
天涯浪人
天涯浪人 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 17:54

    In general, this rule doesn't even have anything to do with pointers. It's just that you can assign values of some type to variables of other types, but not always vice versa. A similar situation would be this:

    double d = 0.0;
    int i = 0;
    
    d = i;    // Totally OK
    i = d;    // Warning!
    

    So that's just something you have to live with.

    0 讨论(0)
  • 2020-12-19 18:02

    That's valid C, but not C++; they are two different languages, even if they do have many features in common.

    In C++, there is no implicit conversion from void* to a typed pointer, so you need a cast. You should prefer a C++ cast, since they restrict which conversions are allowed and so help to prevent mistakes:

    s = static_cast<char*>(p);
    

    Better still, you should use polymorphic techniques (such as abstract base classes or templates) to avoid the need to use untyped pointers in the first place; but that's rather beyond the scope of this question.

    0 讨论(0)
  • 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.

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