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?
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?
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?
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;
}