Here is an example of how a pointer variable of type int is declared: int* pInt; or int *pInt; The two statements above are equivalent. A pointer [9] called pInt [10] of type int is declared. If a pointer stores an address (which is a numeric value), what does its type ( int ) mean? The official term for int in this case is the pointer's 'referent type'. The referent type of a pointer tells the compiler what type is expected at the address which it is storing. Here, we know that pInt stores the address of an int .
It is important to know the referent type of a pointer because when you want to retrieve the int 's value from the address stored in pInt , the compiler only takes into consideration four bytes from that address. [11] On the other hand, if you have a double referent type pointer, the compiler knows that a double value is stored at that address and it retrieves eight bytes to determine the value of the double instead.
The statement below declares two int pointer variables ( not an int pointer called pIntA , and an int value variable called pIntB ): [12]
int *pIntA, pIntB; The * symbol here is used not as a binary multiplication operator, but as a symbol to denote that an int pointer is being declared instead of an int value type. In C#, pointer referent types can only be unmanaged types. The following statement will result in a compilation error: object* pObj; because object is a managed type. A pointer can be of type void* too, although such pointers are not very useful. Why are managed types so called? It is because the .NET CLR is able to relocate managed objects in memory as desired for optimization purposes “ hence they are somewhat 'managed'. Table 29.2 shows what a managed type is, as contrasted with their unmanaged counterparts. The size of a pointer type is system dependent, but the same for all pointer types on a particular system. For example, a pointer of type int* , and another of type char* will take up the same number of bytes to store an address. For most 32-bit systems, the size of a pointer type is four bytes “ wide enough to store a 32-bit address. Like their reference or value cousins, you can apply operators to pointers. Table 29.3 shows the operators which can be applied to pointers in an unsafe context. We shall be covering most of them in the following pages. Table 29.2. Definition of managed and unmanaged types
Table 29.3. Operators that can be applied to pointer types
|