2
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?

0

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

simple as that. @user974967: reading the book will be cheaper in the long run
2

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.

Comments

1

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.