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
.