Reputation: 3215
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.
Upvotes: 2
Views: 179
Reputation: 33029
First, the code you posted has a horrible bug: cptr != 0
should be *cptr != 0
. You should be checking to see if the character at the given address is null, not if the pointer itself is null.
The other answers and comments are correct. The only reason you're getting the correct output is because there happens to be some zeroed memory right at the end of your container array. Putting the container
array inside a struct will help to eliminate the extra padding the compiler might otherwise insert:
#include<iostream>
int main(){
struct {
char container[7];
char alphabet[27];
} x = {
{'a', 'b', 'c', 'd', 'e', 'f', 'g'},
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
};
for(char* cptr = x.container; *cptr != 0; cptr++)
std::cout << *cptr << std::endl;
return 0;
}
If you run this version you'll see your array 'a'
–'g'
printed, then it will run over into the second array and print 'A'
–'Z'
before hitting the null at the end of that string.
Upvotes: 3
Reputation: 101506
You are evoking Undefined Behavior. Undefined Behavior means, "anything can happen," which includes, sometimes, exactly what you want to happen. That's what's happening here.
The reason why you're invoking Undefined Behavior is because you are reading from uninitialized memory, when you access the element one-past-the-end of container
.
Upvotes: 1
Reputation: 96301
You're running off the end of the array which invokes undefined behavior. One possible undefined behavior is that it works in a seemingly reasonable way. In this case probably what's happening is that the undefined behavior is padding your array with zeros.
Upvotes: 2
Reputation: 15397
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.
Upvotes: 8