I should know this, but I don’t and I think its probably a major gap in my foundation knowledge so I thought I should ask the experts.
Given:
char s1[] = { 'M', 'y', 'W', 'o', 'r', 'd' };
char s2[] = "MyWord";
cout << strlen(s1)<<endl;
cout << strlen(s2)<<endl;
cout << sizeof(s1)<<endl;
cout << sizeof(s2)<<endl;
Why when declared as s1 is the strlen 9 but when declared as s2 is is 6? Where does the extra 3 come from, it it the lack of a null terminating character?
And I understand that sizeof(s2) is 1 byte larger than sizeof(s2) because s2 will have the null character automatically added?
Please be gentle, TIA!
char s2[] = "MyWord";Auto adds the null terminator because of the “” declaration.s1declaration does not. When you do astrlenons1and it comes out to 9 it is because it eventually ran into a \0 and stopped.s1shouldn’t be used with strlen since it is not null terminated. strlen on s1 could have been 1,000. If you turn on memory violation detection strlen of s1 would crash.