To save a string of length n in C, you need n + 1 char s. This is because a string in C is just an array of char , terminated by the null character \0 . So the memory that stores the string "hello" looks like
'h' 'e' 'l' 'l' 'o' '\0'
and consists of 6 char , although the word hello is only 5 letters long.
The inconsistency that you see may be semantic; some would say that the length of the word hello is len = 5, so we need to highlight len+1 char s, while some would say that since hello requires 6 char , we have to say that its length (like string C) len=6 .
Please note, by the way, that the way to store C strings is not the only one possible. For example, you can save a string as an integer (giving the length of the string), followed by characters. (I believe Pascal does this?). If you are not using a length field such as this, you need another way to find out when the line will stop. Method C is that the line stops whenever a null character is reached.
To understand how this works, you can try the following:
char* string = "hello, world!"; printf("%s\n", string); char* string2 = "hello\0, world!"; printf("%s\n", string2);
(Purpose char* string = "foo"; is just a shorthand way to create an array with 4 elements and provide the first value of 'f', the second 'o', the third 'o' and the fourth '\ 0 ").
source share