Search code examples
c++arraysconst-char

Cout giving garbage output when looping through a const char


When executing the following code I get what I expect plus some unexpected output:

#include <iostream>

using std::cout;
using std::endl;

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

Output:

h
e
l
l
o
ⁿ
■
m

What are the last remaining characters? Is there something in the const char array that is not being accounted for?


Solution

  • while (*cp)
    

    This loop ends when cp points to a null character.

    const  char ca[] = {'h', 'e', 'l', 'l', 'o'};
    

    The array does not contain the null character.

    Therefore the loop iterates over the array, and outside of its bounds. The behaviour of accessing an array outside of its bounds is undefined.