Search code examples
arrayscstringpointerscasting

Why is integer value of the (n+1)th term in a string is 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;
}

Solution

  • 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.