Pointer Arithmetic
Pointer Arithmetic
There are only two arithmetic operations that you may use on pointers: addition and subtraction. To understand what occurs in pointer arithmetic, let p1 be an integer pointer with a current value of 2000. Also, assume integers are 2 bytes long. After the expression
p1++;
p1 contains 2002, not 2001. The reason for this is that each time p1 is incremented, it will point to the next integer. The same is true of decrements. For example, assuming that p1 has the value 2000, the expression
p1–;
causes p1 to have the value 1998.
Generalizing from the preceding example, the following rules govern pointer arithmetic. Each time a pointer is incremented, it points to the memory location of the next element of its base type. Each time it is decremented, it points to the location of the previous element. When applied to character pointers, this will appear as “normal” arithmetic because characters are always 1 byte long. All other pointers will increase or decrease by the length of the data type they point to. This approach ensures that a pointer is always pointing to an appropriate element of its base type.
You are not limited to the increment and decrement operators. For example, you may add or subtract integers to or from pointers. The expression
p1 = p1 + 12;
makes p1 point to the twelfth element of p1’s type beyond the one it currently points to.
Besides addition and subtraction of a pointer and an integer, only one other arithmetic operation is allowed: You may subtract one pointer from another in order to find the number of objects of their base type that separate the two. All other arithmetic operators are prohibited. Specifically, you may not multiply or divide pointers; you may not add two pointers; you may not aypply the bitwise operators to them; and you may not add or subtract type float or double to or from pointers.
Popularity: 1% [?]