Given the following code:
#include<iostream>
int main(){
char container[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
for(char* cptr = container; *cptr != 0; cptr++)
std::cout << *cptr << std::endl;
return 0;
}
It prints these characters in sequence each time I execute it. I cannot understand why the loop would terminate since I have not explicitly specified any null terminator at the end of the container array. Please help.
It's just luck, really.
It happens that the area of memory corresponding to container[7]
is 0, so you're getting lucky.
Exceeding the bounds of your array is undefined behavior. In your case, it just happens to be the behavior you were hoping for, but you can't rely on that.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments