Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 662
Alex Dannk Avatar asked Apr 21 '12 18:04

Alex Dannk


2 Answers

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)

like image 88
AProgrammer Avatar answered Sep 28 '22 23:09

AProgrammer


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.

like image 45
David Heffernan Avatar answered Sep 29 '22 00:09

David Heffernan