Could you please explain me why the output of the following program is 1?
const char *str = "mms";
printf("%d\n", strlen(str + 2));
return 0;
If I add 1, the result is 2.
For starters this call
printf("%d\n", strlen(str + 2));
can invoke undefined behavior because according to the C Standard (7.21.6.1 The fprintf function)
9 If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
The conversion specifier d
expects an argument of the type int
while the expression strlen( str + 2 )
has the type size_t
according to the declaration of the function strlen
size_t strlen(const char *s);
You have to write
printf("%zu\n", strlen(str + 2));
^^^
You declared a pointer to a string literal
const char *str = "mms";
The string literal is internally is represented as a character array like
{ 'm', 'm', 's', '\0' }
That is it has 4 characters including the terminating zero character '\0'
.
The pointer str
points to the first character of the literal. The expression str + 2
points to the third character of the literal that is to the character 's'
due to the pointer arithmetic.
From the C Standard (7.23.6.3 The strlen function)
3 The strlen function returns the number of characters that precede the terminating null character.
So as the expression str + 2
points in fact to the string "s"
then the function will return 1
that will be outputted.