Reputation: 117
as far as i know, that every string always terminated with '\0',
so my question is
int main()
{
char string1[6]="hello";
// char string2[5]="hello"; // doesnt work
printf("%d",strlen(string));
getchar();
getchar();
return 0;
}
Upvotes: 2
Views: 411
Reputation: 126
Yes, the C language uses '\0' as a sentinel character to find the end of a string. strlen()
returns the length of the string excluding the null character.
You can automatically create a char[]
array of the proper size to hold your string constant (including the null character) by omitting the number inside the brackets:
char string1[] = "hello";
printf("%d", strlen(string1)); // prints 5
This way you can avoid confusion regarding the array length.
To answer question 2: Not if you still want to treat it as a string (i.e. still use the functions in <string.h>
to manipulate it).
Upvotes: 1
Reputation: 206567
Use of the terminating null character allows a program to determine where a string ends. If you didn't have the null terminator, you can determine the length of a string either using a different string terminating character or store the length of the string in the string. Using '\0'
for the terminating null character is most likely historical. That's my guess.
As far as
is there any special case that we are able to end string without
'\0'
?
No. All of the C library functions that work with strings expect the '\0'
. Otherwise, they won't be able to determine which element of an array to stop at. As a consequence, they will end up accessing memory out of bounds.
You can create an array of characters that don't have a terminating null character but that won't be a string.
char arr[2] = {'a', 'b'};
is perfectly fine. You can access arr[0]
and arr[1]
without any problem. However, you can't use arr
as an argument to strlen
. Doing that will lead to undefined behavior.
Upvotes: 2
Reputation: 249123
C style strings are traditionally stored with a null terminator. Functions like strlen()
do not count this null terminator, and give you the "human" length of the string, e.g. "hello" is length 5.
However, you are welcome to store strings without the null terminator if you want; some systems use strings with length prefixes instead, for example, or use strings of fixed capacity with space padding, or other schemes. C doesn't prevent you from doing these things, but if you do, you won't be able to use functions like strlen()
anymore.
Upvotes: 4