New to C++. Question about pointers
I'm using the textbook Beginning Visual C++ 6.0 and so far I find it very good. I'm in chapter 4 and I think I understand pointers, but I have a question about example 10. I've listed the code below. In the 'while loop' a pointer is being incremented. I understand what that is doing, but is there a way, using a 'cout' command to display the address of pbuffer for each character. I'm able to see them by installing a break point and watching pbuffer, but I was wondering if there is a way to code that output?
Thanks.
// EX4_10.CPP
// Counting string characters using a pointer
#include<iostream>
using namespace std;
int main()
{
const int MAX = 80; // Maximum array dimension
char buffer[MAX]; // Input buffer
char* pbuffer = buffer; // Pointer to array buffer
cout << "\nEnter a string of less than " // Prompt for input
<< MAX << " characters: \n";
cin.getline(buffer, MAX, '\n'); // Read a string until \n
// The only way I could figure out how to get the value of
// pbuffer, was to run the program in debug mode and
// install a break point at the 'cout' statement following
// this 'while loop'.
while(*pbuffer) // Continue until \0
{
pbuffer++;
}
// pbuffer - buffer calculates the length of the string.
// pbuffer will contain the address of the last character in the string.
// buffer will contain the address of the first character in the string.
// When you subtract them you get the length of the string.
// In my case the addresses were: pbuffer = 0012FF37 and buffer = 0012FF2C
// The string I entered was 'Hello World'. When you subtract the two addresses
// you get 11 decimal.
cout << "\nThe string \"" << buffer
<< "\" has " << pbuffer - buffer << " characters." << "\n";
return 0;
}
|