What if a null character is present in the middle of a string?

Ranjan Srinivas picture Ranjan Srinivas · Jan 25, 2016 · Viewed 9.2k times · Source

I understand that the end of a string is indicated by a null character, but i cannot understand the output of the following code.

#include <stdio.h>
#include <string.h>

int
main(void)
{
    char s[] = "Hello\0Hi";
    printf("%d %d", strlen(s), sizeof(s));
}

OUTPUT: 5 9

If strlen() detects the end of the string at the end of o, then why doesn't sizeof() do the same thing? Even if it doesn't do the same thing, isn't '\0' A null character (i.e, only one character), so shouldn't the answer be 8?

Answer

Iharob Al Asimi picture Iharob Al Asimi · Jan 25, 2016

The sizeof operator does not give you the length of a string but instead the size of the type of it's operand. Since in your code the operand is an array, sizeof is giving you the size of the array including both null characters.

If it were like this

const char *string = "This is a large text\0This is another string";
printf("%zu %zu\n", strlen(string), sizeof(string));

the result will be very different because string is a pointer and not an array.

Note: Use the "%zu" specifier for size_t which is what strlen() returns, and is the type of the value given by sizeof.