CppPrimer
CppPrimer copied to clipboard
Answer to Exercises 3.37 is not entirely true.
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