On Jul 6, 3:58 pm, k...@bytebrothers.co.uk wrote:
Hello,
Could someone please explain why the (GCC, ancient 2.95.3 version)
compiler won't let me static_cast<a char* to a unsigned char* or
vice versa? It also won't accept dynamic_cast<for those
conversions. The only one it will permit is reinterpret_cast<>.
you cannt use static_cast for casting pointers from one type to
another unless one of them is void* or they are related by
inheritance.
It wont accept dynamic cast either since the two pointers are not
related by inheritance.
BTW, yes I know that pointer casts are 'evil', but here's a for-
example: ostream::write for some reason expects a const char* and a
streamsize parameter, rather than the rather more logical const void*
and a size_t. Many of my applications are mucking around with raw
binary data either in vector<unsigned charor sometimes in raw
unsigned char[], so when I come to write the data out to a file, I
have to cast it to a char*.
Here's a simple example of the problem:
void uc_func(unsigned char *x) {}
void c_func(char *x){}
int main()
{
unsigned char uc[10];
char c[10];
uc_func(uc);
uc_func(static_cast<unsigned char*>(c));
try this: uc_func(static_cast<unsigned char*>(static_cast<void*>(c)));
c_func(static_cast<char*>(uc));
c_func(static_cast<char*>(static_cast<void*>(uc))) ;
c_func(c);}
>
---------------------------------
g++ -g -o x x.cc
x.cc: In function `int main()':
x.cc:17: static_cast from `char *' to `unsigned char *'
x.cc:19: static_cast from `unsigned char *' to `char *'
make: *** [xx] Error 1
g++ -g -o x x.cc
xx.cc: In function `int main()':
xx.cc:17: cannot dynamic_cast `c' (of type `char[10]') to type
`unsigned char *'
xx.cc:19: cannot dynamic_cast `uc' (of type `unsigned char[10]') to
type `char *'
make: *** [xx] Error 1