Sometimes it is necessary (or just convenient) in programs to present array items in the form of the elements of a different type. Dangerous and safe type conversions are shown in the following code.
int array[4] = { 1, 2, 3, 4 }; enum ENumbers { ZERO, ONE, TWO, THREE, FOUR }; //safe cast (for MSVC2005) ENumbers *enumPtr = (ENumbers *)(array); cout << enumPtr[1] << " "; //unsafe cast size_t *sizetPtr = (size_t *)(array); cout << sizetPtr[1] << endl; //Output on 32-bit system: 2 2 //Output on 64 bit system: 2 17179869187 |
As you can see the program output result is different in 32-bit and 64-bit variants. On the 32-bit system the access to the array items is fulfilled correctly for sizes of size_t and int coincide and we see the output "2 2".
On the 64-bit system we got "2 17179869187" in the output for it is value 17179869187 which is situated in the first item of sizetPtr array. In some cases we need this very behavior but usually it is an error.
The correction of the described situation consists in the refuse of dangerous type conversions by modernizing the program. Another variant is to create a new array and copy values of the original one into it.
Comments