0

I am trying to understand pointer arithmetic in C++ but I just don't get it why the below code gives a weird output which I cannot comprehend.

using namespace std;

int main() {
int *p1, *p2;
int x = 100;
int y = 200;
p1 = new int;
p2 = new int;

*p1 = 100;
*p2 = 200;

    cout<<p1<<endl;
    cout<<p2<<endl;

    cout<<p2 - p1<<endl;

    return 0;
}

This gives an output as follows:

0x7fffd46d2e70

0x7fffd46d2e90

8

I do not understand how come p2 - p1 is 8. Which I believe is the size of the pointer. But shouldn't it be 20?? (as calculated below)

0x7fffd46d2e90 - 0x7fffd46d2e70 = 20

or 20 / 2 = 10??

Hope I can get this cleared and some more explanation on pointer arithmetic. Specifically when we subtract an address from another address

pratt33k
  • 1
  • 1

0 Answers0