Explain how sizeof determines the length of the string.
#include<stdio.h>
int main()
{
char str[] = "Sasindar\0Baby\0";
printf("%d\n", sizeof(str));
return 0;
}
Explain how sizeof determines the length of the string.
#include<stdio.h>
int main()
{
char str[] = "Sasindar\0Baby\0";
printf("%d\n", sizeof(str));
return 0;
}
sizeof
does not determine the length of the string. It determines how many bytes a structure takes in memory.
In your case, the structure is str
, an array of bytes. The compiler knows how many bytes, including the two trailing '\0'
s, was placed into the array, so it produces the proper size at compile time. sizeof
has no idea that str
is a null-terminated C string, so it produces 15.
This is in contrast to strlen
, which interprets your string as a C string, and returns the count of characters before the first '\0'
.