user974967
user974967

Reputation: 2946

c++ pointer arithmetic

int a[5];

cout << &a[1] << " " << &a[0] << endl;
cout << (&a[1] - &a[0]);

In the above code, why is &a[1] - &a[0] equal to 1 and not 4? Shouldn't there be 4 bytes between these addresses since we have an int array?

Upvotes: 2

Views: 184

Answers (3)

Adrian Cornish
Adrian Cornish

Reputation: 23858

Pointers are incremented by the size of there type. Reason is because you want to point to the next item. So taking you example further.

int a[5];
int *ptr=&a[0];

// ptr is now pointing at first element.

ptr+3; // now its pointing at 3rd element.

Upvotes: 2

sehe
sehe

Reputation: 392921

To get it in bytes: (see it live https://ideone.com/CrL4z)

int a[5];

cout << (a+1) << " " << (a+0) << endl;
cout << (reinterpret_cast<char*>(a+1) - reinterpret_cast<char*>(a+0));

Upvotes: 1

NPE
NPE

Reputation: 500297

No, pointer difference is in elements, not in bytes.

Upvotes: 8

Related Questions