When i run this code i m getting output as 4. But my string length is 3 why it is giving 4??
#include <stdio.h>
int main(void)
{
printf("%d",sizeof("abc"));
return 0;
}
When i run this code i m getting output as 4. But my string length is 3 why it is giving 4??
#include <stdio.h>
int main(void)
{
printf("%d",sizeof("abc"));
return 0;
}
Character strings in C include a null terminator, so the string "abc" actually occupies 4 bytes.
The type of the string literal "abc"
is char [4]
. It contains the characters a, b, and c, as well as a terminating null byte. The value you're getting back reflects this.
If you want the length of the string, use strlen
.
printf("%zu\n", strlen("abc"));
Note the use of the %zu
format specifier, which expects a parameter of type size_t
, as returned by strlen
(and by sizeof
). Using the wrong format specifier invokes undefined behavior.
Actually you might get undefined behavior
because the sizeof
' operator yields a result of type size_t
,
and %d
isn't necessarily the right format specifier.
Why 4? Because the initialiser is a string literal, it is a string, and does have a null terminator, if it ever exists as an object in memory.
For strings in C I would recommend using the strlen(str1). It returns the length of the string WITHOUT the null termination character.
size_t strlen(const char *str)