简体   繁体   中英

Difference between void pointers in C and C++

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 casting,as p now contains address of char pointer and s is also char pointer?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM