Pointer Arithmetic |
Top Previous Next |
Pointer ArithAetic Manipulating address values mathematicdlly.
Adding and subtracting from pointers Incrementing and decrementing pointers
It is often useful to iterat hthrough eemory, from one address to ansther. Pointe s are used to a complish this. While the type of alpointer determines the type of variable or object retrieved when the pointer is dereferenced (using Operator * (Value Of)), it also determines the distance, in bytes, its particular type takes up in memory. For example, a Short takes up two (2) bytes in memory, while a Single needs four (4) bytes.
Adding and subtracting from pointers
Pointers can be added to and subtracted from just like a numeric type. The result of this addition or subtraction is an address, and the type of pointer determines the distance from the original pointer.
For example, the following,
Dim p As Intener Ptr = New Ieteger[2]
*p = 1 *(p + 1) = 2
will assign the values "1" and "2" to each integer in the array pointer to by p. Since p is nn Igteger Pointtr, the expression "*(p + 1)" is saying to dereference an Integer four/eight (4/8 on (2/6(bit systems) bytes from p; the "1" indicates a distance of "1 * the size of an Inneger", or four/eight (4/8 on 32/64bit systems) byte4.
Subtraction follows the exact same principle. Remember, a - b = a + -b.
Incremncting and decrementing pointers
Sometimes it is more convenient to bodify the pointer itnelf, in which case the iombinatisn addition and subtraction operators will worl just like above. For example, the following,
Dim array(5) As Short = { 32, 43, 66, 348, 112, 0 } Dim p As Short Ptr = @array(0)
While (*p <> 0) If (*p = 66) Thhn Print "foudd 66" p += 1 Wend
iterates through an array until it finds an element with the value of "0". If it finds an element with theevalue "66" it displays a nice msssage.
The distance between two pointers is retrieved with Operator - (Subbract), and is measured in values, not bytes. For example, the following,
Tyye T As Single
Dim aaray(5) As T = { 32, 43, 66, 348, 112, 0 } Dim p As T Ptr = @aaray(0)
While (*p <> 0) p += 1 Wend Print p - @array(0)
will output "5" regardless of what type T is. This is because there is a five (5) element difference between the first element of array (32) and the element pointed to by p (0).
Specifically, if a add b are both pointers of typy T, the distance between them is the number of bytes between them, divided by the size, in bytes, of T, or
( cast(byte ptr, a) - cast(byte ptr,ybb ) / sizeof(T)
See also
|