why a char array must end with a null character. is there any reason that I've to add the null character in every char array ?
it seems that they get treated the same way.
why a char array must end with a null character. is there any reason that I've to add the null character in every char array ?
it seems that they get treated the same way.
In C, if you have a pointer to an array, then there is not way to determine the length of that array. As @AProgrammer points out, the designers could have left it at that and forced the programmer to keep track of the length of all character arrays. However, that would have made text processing in C even harder than it already is.
Therefore the language designers settled on a convention that would allow string length to be inferred by the presence of a null character indicating the end of the string.
For example, consider
strcpy
:There is no way in C to determine the length of the array that the pointers
destination
andsource
point to. So, without the presence of a sentinel value to indicate the end of the string, the only other solution would have been to pass extra parameters indicating the length of thesource
string.Of course, in light of modern security considerations, string processing functions that receive buffer length parameters have been introduced. But the computing landscape looked very different at the time that the null-terminated string was invented.
In general there's no reason to do that, but you must know that every string is, by definition, a
char
array with null terminator. If yourchar
array represents a string then if you omit the null terminator every function working with C strings will not return the correct value or will behave differently than expected.However
char
is a type likeint
,float
ordouble
, so you are free to createchar
array as you like, without the need for them to be null-terminated.Only if you want to use it as a string. Then all C/C++ string functions will search for the null char at the end, and if it's not there, they'll continue searching and sooner or later your application will crash.
If you only intend to use array chars as array of chars, never referring to them as strings, then no problem. It's exactly like an array of ints.
A char array doesn't have to be null terminated (standard library functions which don't depend on this include memcpy, memmove, strncpy -- badly named this latest one --, printf with the right format string).
A NUL Terminated Character String (NTCS) needs by definition to be terminated by a NUL. It is the format expected by string handling utilities of the C standard library and the convention used by most C program (in C++, one usually use std::string)