CppPrimer icon indicating copy to clipboard operation
CppPrimer copied to clipboard

Answer to Exercises 3.37 is not entirely true.

Open glucu opened this issue 3 years ago • 0 comments

Exercise 3.37

Question or Bug

What does the following program do?

const char ca[] = {'h', 'e', 'l', 'l', 'o'};
const char *cp = ca;
while (*cp) {
    cout << *cp << endl;
    ++cp;
}

It's written: Print all the elements of the array. However, there is no null terminator that has a stopping criteria, so it ends up printing all the elements in ca, but continues to traverse past the last element, resulting in a undefined behavior. It should be:

const char ca[] = {'h', 'e', 'l', 'l', 'o', '\0'};
const char *cp = ca;
while (*cp) {
    cout << *cp << endl;
    ++cp;
}

Your enviroment information

  • System: NA
  • Compiler version/IDE: NA

glucu avatar Mar 12 '21 22:03 glucu