I am currently working my way through "C++ Primer". In one the exercise questions it asks:
What does the following program do?
const char ca[] = { 'h', 'e', 'l', 'l', 'o' };
const char *cp = ca;
while (*cp)
{
cout << *cp << endl;
cp++;
}
I am quite happy that i understand *cp will be continue to be true past the last character of the ca[] array because there is no null-character as the last item in the array.
It is more for my own curiosity as to what makes the while-loop become false. It seems to always show 19 characters on my computer. 0-4 are the hello string, 5-11 are always the same, and 12-19 change with each execution.
#include <iostream>
using namespace std;
int main( )
{
const char ca[ ] = { 'h', 'e', 'l', 'l', 'o'/*, '\0'*/ };
const char *cp = ca;
int count = 0;
while ( *cp )
{
// {counter} {object-pointed-to} {number-equivalent}
cout << count << "\t" << *cp << "\t" << (int)*cp << endl;
count++;
cp++;
}
return 0;
}
The question: What causes the while-loop to become invalid? Why is 5-11 always the same character?