String Variable

Hey folks,

I'm new to C++ and taking a cource learning about it. I've been given learning material to learn about C++ and i'm not sure about something compared to other language syntaxes.

The cource material says, if you type this:

char playername[]="Bob";

C++ is counting the number of characters in each string for us and using the length to create array of the correct size to accomodate the string:

char playername[4]="Bob";

The way I understand it is that 'Bob' is 3 characters long so the array should be playername[3] as arrays start with 0.

Thanks
One additional zero byte is added to the end of a string literal. So in fact string literal 'Bob' has four characters.
playername[0] = B
playername[1] = o
playername[2] = b
playername[3] = \0

The \0 is added automatically, so the array is automatically one char longer than what you write
So I am right in my thinking and the course material is wrong? I just need that confirming.
Thanks
yea u are right guest . in your concept . but in fact.
and in TRUE EXPLANATION the array will be [4]
as @maeriden explained .

"\0" will be your last array although your
char[] never insert .
So I am right in my thinking and the course material is wrong? I just need that confirming.
Thanks

The material is right. When you initialize a char array with a string literal the '\0' is automatically added. This means that if the compiler has to determine the size by itself, it reads "Bob\0" which are four characters and create an array of 4 elements
Thanks, Think I understand it now.

I've not used another language that needed an extra a slot for a terminator character.
Null-terminated strings, or c-strings (that's what strings ending with \0 are called) are not exactly mandatory, depending on what you need to do. However most standard library functions expect null-terminated strings as parameters. For example strlen() works by counting how many character there are before it encounters a \0 http://www.cplusplus.com/reference/clibrary/cstring/strlen/
The old C-style strings are best described exactly as they are; null-terminated character arrays. That's exactly what they are and, as maeriden says, the null terminator is implicitly added at the end of the array.

As I said, they're more C-style strings. C++ programmers generally favour the use of the C++ string class. No doubt you'll encounter that in your course somewhere down the line.
Topic archived. No new replies allowed.