How does this count the number of characters ? its the code from a book which I'm reading, although I have added few statements in thisCode:// Ex4_10.cpp // Counting string characters using a pointer #include <iostream> using std::cin; using std::cout; using std::endl; int main() { const int MAX = 80; // Maximum array dimension char buffer[MAX]; // Input buffer char* pbuffer = buffer; // Pointer to array buffer cout << endl // Prompt for input << "Enter a string of less than " << MAX << " characters:" << endl; cin.getline(buffer, MAX, '\n'); // Read a string until \n while(*pbuffer) // Continue until \0 pbuffer++; cout << "\nAddress of pbuffer: " << reinterpret_cast<size_t>(&pbuffer); cout << "\nAddress of buffer: " << reinterpret_cast<size_t>(&buffer) << endl; cout << "\n\nAddress of pbuffer: " << &pbuffer; cout << "\nAddress of buffer: " << &buffer << endl; cout << endl << "The string \"" << buffer << "\" has " << pbuffer - buffer << " characters."; cout << endl; return 0; }
Well pbuffer would be pointing at the last character after the while loop which I think is the null character ('\0')
While buffer is pointing at the first element in the array
So its simple that its difference would produce the number of characters,
I checked its address and on my pc it produced
the following
pbuffer = 1244920
buffer = 1244932
in hex
pbuffer = 0012FEF8
buffer = 0012FF04
so by manual calc of the above values their difference is 12, Right ?
But when used in the cout << statement its not the same ?
how ?