#include <iostream>
using namespace std;
int main()
{
int testNum;
char *ptr;
testNum = 1;
ptr = (char*)(&testNum);
cout << (*ptr);
cin.get();
}
Above is a program to test the endianism of a processor. Since most
PC's are little endian, the answer displayed is usually 1 on a P.C. In
my case (Windows XP, Bloodshed Dev C++) I don't get a 1 but a strange
character which looks a bit like a zero with a smiley inside it.
However, I know that this is essentially right because when I replace
(*ptr) by (*ptr) + 1, I get the expected value of 2. It is only the 1
digit that looks strange. Does anyone know why I get this strange
character? (Or maybe this is OT because it's not a c++ phenomenon.)
The one in "testNum = 1" is not a digit. It is an integral number. '1' would
be a digit and that would be represented as the number 49, at least on a
Windows box. What your program prints is the character with the value 1, and
that might look like a face sticking on some machines. To print a number,
you have to tell your machine to do so:
cout said:
The second question is more c++-related.
I replaced ptr = (char*)(&testNum); by
ptr = static_cast<char*>(&testNum); and got an invalid type conversion.
Why? What is the problem with my line? I thought I was just
translating from C to C++.
A static_cast can convert between related types like ints and chars or
pointers to base classes and pointers to derived classes, but not between
unrelated types like pointers to int and pointers to char. Basically you can
use a static_cast to convert from a type T1 to another type T2 if there is
an implicit or user defined conversion to convert from T2 to T1, or when you
explicitly ask for an implicit conversion in situations where the language
does not require one. As in the example above, the compiler knows how to
print a char, so there's no need to use an implicit conversion, but if you
want the it to print the character's value, you have to say so, explicitly
casting the char to an int.
Apparently static_cast can't cast from type int* to type char*. What's
the general rule about when you can static_cast and when you can't?
If you have to cast, try a static_cast first. If the compiler complains,
think about what you want to do and once you are sure you know what you are
doing, use reinterpret_cast.
HTH
Heinz