How is the value of b[5] (i.e the term next to the last term) is equal to 0 ? However b[6] gives some random number.
#include <stdio.h>
int main()
{
char *b = "HELLO";
printf("%d",b[5]);
return 0;
}
How is the value of b[5] (i.e the term next to the last term) is equal to 0 ? However b[6] gives some random number.
#include <stdio.h>
int main()
{
char *b = "HELLO";
printf("%d",b[5]);
return 0;
}
C-strings are null terminated. That's why when you print it like an integer it gives 0.
If you do:
if(b[5] == '\0')
printf("null detected\n");
then "null detected" will be printed.
The reason is that strings are passed as pointers and their size is not known/passed. So all functions use the null character to detect the end, as commented by @Downloadpizza.
You should not access the memory past the null terminator, since this is like accessing an array out of bounds.
C language uses "NULL TERMINATION" for the end of the string. and its value corresponds to '0'.(ASCII for NUL = 0) (by definition).
Note: , your string starts from
b[0]- H , b[1]- E , b[2]- L , b[3]- L , b[4]- O , b[5]- \0 [NULL Termination].
so b[5] corresponds to 6th byte and since it is end of string. it corresponds to NUL(\0)
refer to link for further details: [C Strings]
C uses a null character to mark the end of a string. A null character is a character with the value zero.
A null character is automatically added to the end of a string literal, so "HELLO"
consists of characters for the letters H, E, L, L, O, and a null character.
b[6]
would be the character beyond the end of the string. Since this is not part of the string, the memory there was not set as part of initializing the string. It might be other data in your program (including data you do not normally see because it is part of the behind-the-scenes software that supports C programs), and the behavior of accessing it is not defined by the C standard. Accessing it could damage your program in various ways.