3

I have a function that returns a const void* and I'd like to use its information as a char*. I can cast it C-style fine as (char *)variable but when I try to use reinterpret_cast like reinterpret_cast<char *>(variable), I get a compilation error.

Should I use a different casting method?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
jijemi
  • 43
  • 1
  • 5

3 Answers3

5
const void *p;
void *q = const_cast<void *>(p);
char *r = static_cast<char *>(q);

The first cast gets rid of const and yields a void *

The second cast changes the data type and yields a char *

Read about the different C++ casts here

Sid S
  • 6,037
  • 2
  • 18
  • 24
1

Either reinterpret_cast<const char*>(variable) or, if you really are absolutely sure you can ignore the const qualifier, const_cast<char*>(reinterpret_cast<const char*>(variable)).

Davislor
  • 14,674
  • 2
  • 34
  • 49
0

Using reinterpret_cast<char*>() for simple types is not a good idea. Use const char *new_variable = static_cast<const char*>(variable).

Also it is a bad idea to remove const. If you absolutely sure that the returned memory is writable, you can use then const_cast<char*>(new_variable).

273K
  • 29,503
  • 10
  • 41
  • 64