'Why do I get a negative number when subtracting pointers?

The following program gives -1, but I expected it to print 1:

#include <iostream>
int main()
{
    int a[] = {0, 1};
    int* p = a;
    int* p2 = a+1;

    std::cout << p - p2 << std::endl;
    system("PAUSE");
    return 0;
}

If I swap the subtraction around like this:

std::cout << p2 - p << std::endl;

Then I get exactly 1.

The answer to Pointer subtraction confusion says that if we subtract pointer from pointer, we get the amount of blocks of memory lying between them, and I don't see that this can be negative.

I'm expecting to get exactly the same result for p - p2 and p2 - p.



Solution 1:[1]

You get -1 because that is the amount you must add to p2 to reach p. Subtraction is the inverse operation to addition.

Pointer arithmetic works in units of the pointed-to type, in this case int. p is set to point to a[0] and p1 points to a[1]. In other words, p + 1 == p2 and p2 - 1 == p.

Pointer types in C++ are an abstraction, and like all abstractions, it's best (most of the time) to use the abstraction - in this case, that means not needing to worry about machine addresses and the size of types when doing pointer arithmetic. If you ensure that the type is correct, then you can step through arrays simply by the number of elements, regardless of their size.

It is useful to understand how the abstraction is implemented by the machine, and essential to know when you need to look 'under' the abstraction; such situations include union types and the use of reinterpret_cast<>().

Solution 2:[2]

From the C++ Standard definition of pointer subtraction:

When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements.

"difference" means subtraction. So in code this says that &arr[X] - &arr[Y] is X - Y. This could be positive or negative depending on whether X or Y is greater.

In your code a means &a[0], and a+1 means &a[1]. So when you do a - (a+1) it is the same as &a[0] - &a[1], which is -1 according to the above rule.

Solution 3:[3]

Maybe think about it this way. Subtracting two pointers such as p1 - p2 yields the number that, when added to p2 yields p1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 M.M
Solution 3 Dharman