0

Here is my code:

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

Output:

h e l l o  `

Why is there some char value at the end of the array?

Cœur
  • 37,241
  • 25
  • 195
  • 267
hashmap
  • 400
  • 1
  • 9
  • 3
    went out of bounds, add a `\0` character at end of array... – t0mm13b May 23 '17 at 20:40
  • 1
    When you write `{'h','e','l','l','o'}` instead of `"hello"`, the compiler doesn't add a "nul terminator" for you. – zwol May 23 '17 at 20:41
  • To loop over that char array without adding '\0': `for(size_t i = 0; i < sizeof(ca)/sizeof(ca[0]); ++i){ std::cout << ca[i] << ' '; }` – zett42 May 23 '17 at 20:50
  • 1
    If you can use C++11 then it will be even simpler: `for(auto c: ca){ std::cout << c << ' '; }` – zett42 May 23 '17 at 20:52

2 Answers2

2

You are invoking Undefined Behavior, since you do:

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

without having a null terminator appended to your string. As a result you are going out of bounds, meaning that you are accessing memory that does not belong to that array, thus the non-expected character you see.

To add a null terminator, simply do this:

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

Good read: How dangerous is it to access an array out of bounds?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • that make sense! But then how does the loop terminates? – hashmap May 23 '17 at 20:45
  • @NimitPatel when you go out of bounds, the loop will continue up to a point, where the condition of the while loop gets false. Otherwise it will cause a segmentation fault, most likely! I updated my answer! ;) – gsamaras May 23 '17 at 20:50
0

You should put '\0' as the last element in your array, otherwise while(*cp) is always true until null terminator '\0' is encountered by coincidence.

try:

const char ca[] = {'h','e','l','l','o','\0'};
    const char* cp = ca;
    while(*cp){
        std::cout<<*cp<<" ";
        ++cp;
    }
Shadi
  • 1,701
  • 2
  • 14
  • 27