1

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 :

  1. 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?

  2. 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 :)

1
  • 2
    You're incrementing messPt in the while() conditional and only after you stream it into cout... Commented Dec 27, 2013 at 22:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh thanks :) .. actually the while (*messPtt++ != '\0) , is given by the text book. The exercise ask to modify the previous exercise (which is using a for loop) to the while loop . Btw thanks for knowledge :) ... really appreciate it..
Oh one more thing : What is the different between char *messPt; messPt = &strng[0]; and messPt = strng; I know that, for the first declaration, it means that the messPt is pointed to the address of the first array, but does it works same as the second declaration?
@user3040961, the declaration char *messPt and char strng[] are somewhat equivalent. They are two ways of looking at the same thing: an array (sequence) of chars. So messPt = strng is essentially setting the messPt pointer to the same memory location strng is pointing to (i.e. the start of the array). On the other hand messPt = &string[0] is basically a somewhat convoluted way of doing the same as the above but it goes about it indirectly: the ampersand takes the address of strng[0] which in turn, dereferences strng.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.