Last active
October 16, 2020 19:52
-
-
Save HackerFoo/3e1ccd5872a1149c54330942a88a595d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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