1. String Literals Include a Null Terminator
When you write "Hello"
, the compiler automatically appends a null character (\0
) at the end to indicate the end of the string.
So, "Hello"
in memory is actually:
['H', 'e', 'l', 'l', 'o', '\0']
Thus, sizeof("Hello")
counts all 6 bytes, including the \0
2. Difference Between sizeof and strlen
sizeof("Hello")
returns 6
at compile-time because it includes the null terminator
strlen("Hello")
returns 5
at runtime because it counts only characters until \0
Example:
#include <stdio.h>
#include <string.h>
int main() {
printf("sizeof: %lu\n", sizeof("Hello")); // Output: 6
printf("strlen: %lu\n", strlen("Hello")); // Output: 5
return 0;
}
How to Avoid This Confusion?
Use strlen()
when you need the actual string length
Use sizeof()
only if you need memory size allocation, such as for a character array