Lately I’ve been doing a lot of exercises with file streams. When I use fstream.write(...)
to e.g. write an array of 10 integers (intArr[10]) I write:
fstream.write((char*)intArr,sizeof(int)*10);
Is the (char*)intArr-cast safe? I didn’t have any problems with it until now but I learned about static_cast (the c++ way right?) and used static_cast<char*>(intArr) and it failed! Which I cannot understand … Should I change my methodology?
A static cast simply isn’t the right thing. You can only perform a static cast when the types in question are naturally convertible. However, unrelated pointer types are not implicitly convertible; i.e.
T*is not convertible to or fromU*in general. What you are really doing is a reinterpreting cast:In C++, the C-style cast
(char *)becomes the most appropriate sort of conversion available, the weakest of which is the reinterpreting cast. The benefit of using the explicit C++-style casts is that you demonstrate that you understand the sort of conversion that you want. (Also, there’s no C-equivalent to aconst_cast.)Maybe it’s instructive to note the differences:
Off-topic: The correct way of writing the last line is a bit more involved, but uses copious amounts of casting: