简体   繁体   中英

Why must a char array end with a null character?

Why does a char array have to end with a null character? Is there any reason that I have to add the null character to to every char array ?

It seems that they get treated the same way.

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 )

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 :

char *strcpy(char *destination, const char *source);

There is no way in C to determine the length of the array that the pointers destination and source 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 the source 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.

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.

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 your char 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 like int , float or double , so you are free to create char array as you like, without the need for them to be null-terminated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM