Reputation: 95
Why does c-string length matter when using for loops? Is there an issue with the termination character '\0'?
The following code sends the for loop into a crazy loop that crashes the compiler:
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
char c[] = "charac";
int i;
for (i=0; i < 8 ; i++)
{
cout << c[i] << endl;
}
return 0;
}
By adding a 't' to my c-string, the code runs perfectly fine:
char c[] = "charact";
int i;
for (i=0; i < 8 ; i++)
{
cout << c[i] << endl;
}
Upvotes: 0
Views: 136
Reputation: 43
c[7] doesn't exist for "charac" as c[6] is the null terminating character. But when you change it to "charact" then c[7] becomes the null terminating character so it runs fine.
Upvotes: 0
Reputation: 31
You are index past the end of the array. C starts indexing at zero so the last index of a six character string is five. If you include the null terminator then you have six but you are accessing the seventh array position.
Upvotes: 1
Reputation: 281496
In your first version, there is no character c[7]
. You have 7 characters in the array, 6 characters of string and 1 null terminator:
Array: c h a r a c \0
Indices: 0 1 2 3 4 5 6
Attempting to access anything beyond that is undefined behavior.
In your second version, assuming the code you're running has the t
you forgot to put in the posted version, the array has 8 characters, and the loop stays within the bounds of the array.
Upvotes: 2
Reputation: 251
I think that you are stepping past the end of the end of your character array. By adding the extra character, your string is now 7 characters long so the i<8 test works.
Upvotes: 1
Reputation: 15870
You have a string of length 7 (6 + null terminator), and are attempting to access an 8th element. This will result in undefined behavior.
Upvotes: 1