Subtracting Pointers

Pointer variables pointing to the same built-in array may be subtracted from one another. For example, if vPtr contains the address 3000 and v2Ptr contains 3008, the statement

x = v2Ptr - vPtr;

would assign to x the number of built-in array elements from vPtr to v2Ptr—in this case, 2. Pointer arithmetic is meaningful only on a pointer that points to a built-in array. We cannot assume that two variables of the same type are stored contiguously in memory unless they’re adjacent elements of a built-in array.

Image Common Programming Error 8.4

Subtracting or comparing two pointers that do not refer to elements of the same built-in ...

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.