In C, all the strings have a null terminator, which is the character '\0
' at the end of string. This character also occupies memory, and because of this, it is part of the string and there should be room reserved for him in array character.
The character '\0
' is nothing more than the zero value represented as a character (see in ascii table). In C, the strings use it to represent where the string ends.
Thus the string "Linguagem C.
" have 12 characters, but counting with the terminator '\0
' there will be 13, so a array 13 positions to store this string.
In C, there is the function strlen
which gives the length of a string not counting the null terminator. But note that this function computes the size of the string by scrolling through all your characters one by one looking for the null terminator, then if your string is very large (a whole book, for example), it will be slow, and so it is better to avoid using it if you can get the size of the string in some other more efficient way.
And as pointed out by Jonny Piazzi in a comment, since the strlen
just search for the null terminator, the size of the array in itself does not matter. This way if you use a array 20 characters to store a string with only 12, what will import will be the position where the null terminator will be found.
Also keep in mind that strlen computes the size of your valid string. If you have a 12-character string within a 20-position char array yet strlen returns 12.
– Jonny Piazzi
@Jonnypiazzi Thank you, I complemented my text with your comment. :)
– Victor Stafusa
I’ll see this strlen when studying strings.
– user25145