Hello im confused by typecasting pointers. I understand that void can hold any type.
So if i have an int * with a value inside of it then i make a void * to the int * can i then typecast it to a char?
It's quite hard to explain what i mean and the title might be wrong but will this work?
And is it safe to do this. I've seen it used quite alot in C. Is this bad practise.
int main() {
int* a = new int{ 65 };
void* v = static_cast<int*>(a);
std::cout << *(static_cast<char *>(v));
}
CodePudding user response:
I understand that void can hold any type.
You understand it wrong. Pointer does not hold data, it points to it. So integer pointer points to memory with holds integer, float pointer points where float is etc. Void pointer just points to some memory, but it says - I do not know what kind of data is there.
Now conversion. Technically you can convert almost any pointer to any (there are exceptions like function pointers or pointers to a member, but they are completely different beasts and it is not what you are asking about) as they all just pointers. But problem happens when you try to access memory where they point to. So if you have int
in memory and try to read it as float
or vice versa - that's illegal. Now therte is one exception - you can access any data through pointer to char
(or unsigned char
) as char
represents byte
. Void pointer is irrelevant here, you can convert from pointer of one type to another without void *
involved:
int main() {
int* a = new int{ 65 };
unsigned char *uptr = reinterpret_cast<unsigned char *>( a );
for( size_t i = 0; i < sizeof(int); i )
std::cout << static_cast<unsigned int>( uptr[i] ) << ' ';
}
Note I casted uptr[i]
to unsigned int, that is to print bytes as numbers, as C stream ( std::cout
in this case) will print character as symbol, which would be meaningless in this case.