In conventional arithmetic, the addition 3000 + 2
yields the value 3002
. This is normally not the case with pointer arithmetic. When an integer is added to, or subtracted from, a pointer, the pointer is not simply incremented or decremented by that integer, but by that integer times the size of the object to which the pointer refers. The number of bytes depends on the object’s data type. For example, the statement
vPtr += 2;
would produce 3008
(from the calculation 3000 + 2 * 4
), assuming that an int
is stored in four bytes of memory. In the built-in array v
, vPtr
would now point to v[2]
(Fig. 8.16). If an integer is stored in eight bytes of memory, then the preceding calculation would result in memory location 3016
(3000 + 2 * 8
).
If vPtr
had been incremented to 3016
, which points to v[4]
, the statement
vPtr -= 4;
would set vPtr
back to 3000
—the beginning of the built-in array. If a pointer is being incremented or decremented by one, the increment (++
) and decrement (--
) operators can be used. Each of the statements
++vPtr;
vPtr++;
increments the pointer to point to the built-in array’s next element. Each of the statements
--vPtr;
vPtr--;
decrements the pointer to point to the built-in array’s previous element.
Error-Prevention Tip 8.5
There’s no bounds checking on pointer arithmetic. You must ensure that every pointer arithmetic operation that adds an integer to or subtracts an integer from a pointer results in a pointer that references an element within the built-in array’s bounds.
3.146.221.144