Skip to content

Instantly share code, notes, and snippets.

@HackerFoo
Last active October 16, 2020 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HackerFoo/3e1ccd5872a1149c54330942a88a595d to your computer and use it in GitHub Desktop.
Save HackerFoo/3e1ccd5872a1149c54330942a88a595d to your computer and use it in GitHub Desktop.
// To compile: clang++ -std=c++11 ptrdiff.cpp -o ptrdiff
// To run: ./ptrdiff
#include <vector>
#include <numeric>
#include <cassert>
#include <iostream>
int main() {
// Create a vector where v[x] == x
std::vector<int> v(100);
std::iota(v.begin(), v.end(), 0);
// &v[0] - first == 0 --> first = &v[0]
int *first = &v[0];
for(int &e : v) {
// Vectors are stored in contiguous memory, like a C array.
assert(&e - first == e);
}
std::cout << "All good." << std::endl;
return 0;
}
// NOTE: Pointers are assumed to be within &v[0] to &v[v.size() - 1],
// so if this assumption can be violated, you may need to check it.
// Unaligned pointers will be rounded down.
// For pointers, `(T *)a - (T *)b` is equivalent to `((char *)a - (char *)b) / sizeof(T)`,
// but the division can be computed efficiently as a shift when sizeof(T) is a power of 2.
// So it might be worth ensure that.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment