Click to See Complete Forum and Search --> : reinterpret_cast


anadi_indian
November 28th, 2005, 12:29 AM
Can anyone look at it and help me figure out how a reinterpret cast works?

Here is the code :

main()
{

int * ptr;
int i = 20;
ptr = &i;
cout<<ptr<<endl;
i = reinterpret_cast<int>(ptr);
cout<<i<<endl;

int * ptr1;
int i1 = 200;
ptr1 = &i1;
cout<<ptr1<<endl;
i= reinterpret_cast<int>(ptr1);
cout<<i1<<endl;

char* a = " This is a string";
i = reinterpret_cast<int>(a);
cout<<&a[0]<<endl<<i<<endl;

char* a1 = "This is something else";
i1 = reinterpret_cast<int>(a);
cout<<&a1[0]<<endl<<i1<<endl;



}


and here is the o/p:


0012FF78
1245048
0012FF70
200
This is a string
4636728
This is something else
4636728
Press any key to continue


How does it work ??
Whats happenin?

cilu
November 28th, 2005, 03:23 AM
reinterpret_cast Operator (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang/html/_pluslang_reinterpret_cast_operator.asp)

and

reinterpret_cast Operator (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/express_76.asp)

Graham
November 28th, 2005, 03:55 AM
i= reinterpret_cast<int>(ptr1);
cout<<i1<<endl;

I think you have a typo in these two lines. Didn't you mean to cout "i", not i1?

Basically, reinterpret_cast takes whatever you put between the "()" and treats it as if it were of the type specified between the "<>".

Don't be confused, BTW, that outputting a pointer generates hex, whereas outputting an integer generates decimal.

SuperKoko
November 28th, 2005, 06:43 AM
There are basically two things to understand in your program:


reinterpret_cast works on pointers or integers of the same size (for example 4 bytes), and do no special treating on them. So, it does not really convert a value to another, but interprets a value as a value of another type.
cout (which is an instance of basic_ostream<char> class) overloads operator>> for different types.
And each type has a different interpretation and representation by this operator.


With cout, integers are displayed in decimal format (this behavior can be modified, using a manipulator or setting a bit mask).
With cout, pointers other than const char* are outputed as the address contained in the pointer in hexadecimal format.
And, finally, there is an overload for const char* which outputs each character pointed by the pointer and above the address pointed by the pointer, until a '\0' character is found.

0012FF78 is the address of i displayed in hexadecimal format.
1245048 is the same address, but displayed in decimal format (you can verify with calc.exe).
0012FF70 is the address of i1 in hexadecimal format.

4636728 is the address of the first string, displayed in decimal format.