Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a const void*

Tags:

c++

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?

like image 530
jijemi Avatar asked Oct 30 '25 01:10

jijemi


2 Answers

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

like image 91
Sid S Avatar answered Nov 01 '25 13:11

Sid S


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)).

like image 32
Davislor Avatar answered Nov 01 '25 15:11

Davislor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!