Reputation: 27
I am trying to improve my programming skill and i've tried the exercise in my text book. I would like to ask a questions here:
char strng[] = " Hooray for All of Us ";
char *messPt;
messPt = &strng[0];
for(int i=0;i<20;i++)
cout << *(messPt + i) << " ";
cout << endl;
messPt = strng;
while(*messPt++!= '\0')
cout << *messPt ;
cout << endl;
and this is the output :
H o o r a y f o r A l l o f U
Hooray for All of Us
My questions are :
actually at the end of the second output , there is a ? but it's in the reverse form. May anyone explain to me why this happen?
if i declare the char like this : char strng[] = "Hooray for All of Us"; The second output become like this : ooray for All of Us
Thanks in advance :)
Upvotes: 1
Views: 93
Reputation: 55720
That's because you are incrementing messPt
when testing whether you've reached the end of the string in the while loop's condition:
while(*messPt++ != '\0') // tests *messPt = '\0' and also advances messPt by one
cout << *messPt ;
You can refactor that to:
while(*messPt != '\0')
{
cout << *messPt ;
messPt++;
}
Or, if you are keen on being clever you can change it to this:
while(*messPt != 0)
cout << *messPt++;
Sometimes the ++
operator can cause lots of hidden bugs. That's why some people argue it should be used sparingly.
Upvotes: 1