Reputation: 1518
I want to find out the "distances" between locations of consecutive vector elements in the memory. So I try the following code
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec(3);
for (int i = 0; i <= 1; i++)
{
cout << &vec[i+1] - &vec[i] << endl;
}
return 0;
}
The result are unsurprisingly two 1
s. However, when I try printing the individual pointers:
vector<int> vec(3);
for (int i = 0; i <= 2; i++)
{
cout << &vec[i] << endl;
}
The result is
01485048
0148504C
01485050
So the difference between two consecutive elements should be 4
. Seemingly a contradiction to the previous result. What goes wrong here?
Upvotes: 0
Views: 139
Reputation: 179981
Nothing particular to vector
. C++ pointer arithmetic (and iterator arithmetic) is done in terms of elements. And indeed, vec[i+1]
and vec[i]
are one element apart.
One element here happens to be 4 bytes, which is what you see when printing the bit pattern of the pointers. You can double-check this with sizeof(vec[0])
Upvotes: 4
Reputation: 37600
You should cast pointers to uintptr_t
so substraction will yield amount of bytes in between them:
cout << (reinterpret_cast< uintptr_t >(&vec[i+1]) - reinterpret_cast< uintptr_t >(&vec[i])) << endl;
Upvotes: 1
Reputation: 136
Calculating a difference between two pointers returns number of objects between them - that's why you cannot perform arithmetic on two pointers of different types. If you want to know the distance of bytes between them, either cast both pointers to char*
or multiply the result of substraction by sizeof(your_type)
.
Upvotes: 1