reinterpret_cast<>

1
2
3
4
5
6
7
8
9
10
11
12

int main ()
{
	int a = 100, *pt = &a;
	char ch = 'A';

	cout << "as an integer pointer: " << *pt << endl;
	pt = reinterpret_cast<int*>(&ch);
	cout << "as a character pointer: " << *pt << endl;

	return 0;
}


I was expecting to get 'A' as the output of line 9. But, for some reason, I got a HUGE number instead.

So can anyone explain what is wrong with the code, please?
You aim a pointer to int at a char and wonder what is wrong?

Don't do that.

Aim pointers to int at ints, and pointers to char at chars.

Hope this helps.
I know I was aiming a pointer to int at a char. But I DID use reinterpret_cast<>.
I mean, shouldnt reinterpret_cast<> "cast" pt into a pointer to a char????
Last edited on
I mean, shouldnt reinterpret_cast<> "cast" pt into a pointer to a char????


No. &ch already is a pointer to a char. You're casting it to a pointer to an int.

Line 9 ends up taking the data at 'ch' (As well as some data after it because ints are larger than chars -- of which the results are undefined) and interprets that data as if it were an integer.

Which is why you're getting a crazy garbage number instead of a character.


EDIT:

I reread what you said...

reinterpret_cast doesn't change 'pt', it changes what's in the parenthesis (in this case '&ch')

pt is still an int*. What you're doing is changing &ch from char* to int*
Last edited on
Oh yeah, sorry! What I meant was
"shouldn't reinterpret_cast<> "cast" pt into a pointer to an int????"
Okay, I see what you mean!
It absolutely does, but that does not mean the data it points to changes from char to int.
Topic archived. No new replies allowed.