Skip to content

Answer to Exercises 3.37 is not entirely true. #198

@glucu

Description

@glucu

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions