help me understand this example

when reading my C++ book (Beginning Visual C++ 2008 by Ivor Horton) i came across this example, and i just cant seem to understand it. it goes like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
	const int MAX = 80;
	char buffer[MAX];
	char* pbuffer = buffer;

	cout << endl
		<< "Enter a string of less than "
		<< MAX << " characters: "
		<< endl;

	cin.getline(buffer, MAX, '\n');

	while (*pbuffer)
		pbuffer++;
	 
	cout << endl
		<< "The string \"" << buffer
		<< "\" has " << pbuffer - buffer << " characters.";
	cout << endl;
	return 0;
}


what is the condition for the while loop, what is incrementing pbuffer doing and why is the number of characters in the statement pbuffer - buffer.

thank you!!!
closed account (D80DSL3A)
All of your questions are answered on page 192 in the section titled How it Works.
Read it carefully.
i read it several times and couldnt really grasp it so i was hoping that someone else could provide a different perspective?
For a one dimensional array the name of the array functions as a pointer to the first element of the array. On line 10 pbuffer is a character pointer that is initialized to buffer and hence points to the first element of the array buffer.

In the condition of a while loop any non-zero value evaluates to true and zero evaluates to false. On line 19 the condition *pbuffer dereferences the pointer and hence first time through the loop has the value of the first character in the array. In the body of the while loop pbuffer is incremented until it points to the terminating null or '\0' character of the array at which point the condition is false and the loop ends. At this juncture buffer points to the first element of the array and pbuffer points to the terminating null.

On line 24 the expression pbuffer - buffer is nothing but pointer arithmetic which yields the number of character values between the two pointers. Since arrays are guaranteed to be allocated in contiguous memory this gives the length of the string stored in the array buffer.

Note that the call to cin.getline(buffer, MAX, '\n'); will not read more than MAX - 1 characters because it reserves the final character of the array for the terminating null.
Topic archived. No new replies allowed.