C program - size of string with characters \ 0

Explain how sizeof determines the length of a string.

#include<stdio.h>

int main()
{
    char str[] = "Sasindar\0Baby\0";
    printf("%d\n", sizeof(str));
    return 0;
}

      

+3


source to share


1 answer


sizeof

does not determine the length of the string. It determines how many bytes the structure occupies in memory.

In your case, a structure str

, an array of bytes. The compiler knows how many bytes, including the two trailing '\0'

s, were placed into the array, so it creates the correct size at compile time. sizeof

has no idea what str

a null terminated string C is, so it produces 15.



This is different from strlen

which interprets your string as a C string and returns the number of characters before the first '\0'

.

+6


source







All Articles