Why exactly does this work to get the position of a char inside a string?
http://codepad.org/HOX9DT3zCode:#include <iostream> #include <cstring> using namespace std; int main() { char axle[] = "axle"; char* start_ptr = strchr(axle, 'a'); size_t start_pos = start_ptr - axle; cout<< "start_pos = " << start_pos <<endl; start_ptr = strchr(axle, 'x'); start_pos = start_ptr - axle; cout<< "start_pos = " << start_pos <<endl; start_ptr = strchr(axle, 'l'); start_pos = start_ptr - axle; cout<< "start_pos = " << start_pos <<endl; start_ptr = strchr(axle, 'e'); start_pos = start_ptr - axle; cout<< "start_pos = " << start_pos <<endl; return 0; }
My confusion arises from "start_ptr - axle", since start_ptr is a char pointer storing an address of a char element of a char array, and I can't see why subtracting the array "axle" from that would result in getting the correct position/index number (though counting from 0, since its an array) of a char inside a char array. I know identifiers for arrays are really just referring to pointers to the first element of the array, but even if you think of one memory address subtracting another from it, it still wouldn't be single digit numbers like 0, 1, 2, and 3.