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 from U*
in general. What you are really doing is a reinterpreting cast:
int intArr[10];
myfile.write(reinterpret_cast<const char *>(intArr), sizeof(int) * 10);
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 a const_cast
.)
Maybe it's instructive to note the differences:
float q = 1.5;
uint32_t n = static_cast<uint32_t>(q); // == 1, type conversion
uint32_t m1 = reinterpret_cast<uint32_t>(q); // undefined behaviour, but check it out
uint32_t m2 = *reinterpret_cast<const uint32_t *>(&q); // equally bad
Off-topic: The correct way of writing the last line is a bit more involved, but uses copious amounts of casting:
uint32_t m;
char * const pm = reinterpret_cast<char *>(&m);
const char * const pq = reinterpret_cast<const char *>(&q);
std::copy(pq, pq + sizeof(float), pm);