29.6 Using the address-of operator


29.6 Using the & address-of operator

The & symbol is used as the binary AND operator when placed between two numbers , or the logical (boolean) AND operator when placed between two boolean values. But when used in unsafe codes, & becomes the 'address-of' operator.

Let's look at the following two statements:

 10: int myInt = 3; 11: int* pInt = &myInt; 

&myInt means 'the address of myInt '. What is happening is that the address of this int variable is being assigned to be stored in pointer pInt . Since an address is simply a number, you can do something like this in C#:

 int* pAny = (int*)0x123456; 

but statements like the one above are senseless and dangerous unless you are certain of what is stored at 0x123456.

When you create a variable and assign a value to it, the value gets stored at some location in the computer's memory. Each memory location has an address, much like houses along a street have unique addresses. A typical memory map is shown in Figure 29.2.

Figure 29.2. Part of the memory map of a construed example.

graphics/29fig02.gif

Figure 29.2 shows a snapshot of what is currently stored in locations 0x9901 to 0x990E . Notice that addresses are usually shown in hexadecimal format, and that a 32-bit machine is used for this example. Each location can store one byte of information.

When the statement int myInt = 3 ; runs, a section of memory is reserved for storing an int value. An int in C# is a 4-byte- sized numeric value. Assuming the address 0x990A has been selected, the statement would result in the memory map shown in Figure 29.3.

Figure 29.3. int variable myInt 's value of 3 is stored at 0x990A.

graphics/29fig03.gif

When you declare a pointer with the int* pInt; statement, another location is reserved for pInt . Since this is a 32-bit system, I shall assume that four bytes are used to store an address. Hence pInt takes up four bytes of space as well. [13] Let's assume that pInt is allocated the address slot at 0x9906 , and since the address of myInt is assigned to it, this results in the new memory snapshot shown in Figure 29.4. pInt is 'pointing' to where myInt 's value is stored.

[13] Remember that this is not because its referent type is int . A pointer of type double* will also take up four bytes of space.

Figure 29.4. Pointer variable pINT is stored at 0x9906 . It contains the value 990A “ the address of where variable myInt 's value is stored.

graphics/29fig04.gif



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