29.11 Pointer casting


You can cast pointer types. Casting has to be done explicitly since pointer types are not related by a common class hierarchy. The only exception to this rule is a cast from any pointer type to void* “ this can be done implicitly.

Here is an example of casting an int pointer to a long pointer type:

 1: using System;  2:  3: public class TestClass{  4:  5:   public unsafe static void Main(){  6:     int myInt = 3;  7:     int* pInt = &myInt;  8:  long* pLong  =  (long*) pInt;  9: 10:     long myLong = *pLong; 11:     Console.WriteLine(myLong); 12:   } 13: } 

Output: [16]

[16] Output will vary.

 c:\expt>test 8727635315138756611 

This is a nonsensical output. Line 8 performs a pointer type cast. Casting pointers does not change the value stored in a pointer (remember that all pointers take up the same number of bytes in a particular operating system, regardless of its referent type). This implies that pLong and pInt store the same value (an address of myInt ). The difference is that because of the pointer's referent type, a long* pointer will attempt to retrieve eight bytes from the address it stores when dereferenced, while an int* pointer will attempt to retrieve only four bytes from the same address and make sense out of it.

On line 10, myLong is assigned eight bytes stored at the address it contains. The first four bytes will encode the value 3 , but it is not certain what the next four bytes contain. When the eight bytes are interpreted together as a long value, it is not surprising that a long value is produced which doesn't make sense.

You do not usually perform pointer type casting unless you know what you are doing, and are very sure of the address boundaries you use to store values. Pointer casting from a referent type of wider range to one of a narrower range might be useful, such as in the scenario where you are interested in only the first four (more significant) bytes of a 8-byte long value.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net