momo momo - 4 months ago 18
C Question

Can't understand strlen expression argument result

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main(){
char p[]="CALIFORNIA\n";
printf("%s\n",p );
printf("%lu\n",strlen(p) );
char *x ="HELLO";
printf("%s\n",x);
printf("%lu\n",strlen(x) );
printf("%lu\n",sizeof(p) );
printf("%lu\n",sizeof(x) );
printf("%lu\n",strlen(p+sizeof(p)-sizeof(x)+5) );
}


I searched all over but couldn't find what happens when the argument of strlen is an expression. The result is 2 for the last statement,can anyone please explain how?

Answer Source

There is used the pointer arithmetic. To make it more clear just run this demonstrative program.

#include <stdio.h>
#include <string.h>

int main(void) 
{
    char *x ="HELLO";
    const size_t N = strlen( x );

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%zu - %s\n", strlen( x + i ), x + i );
    }

    return 0;
}

Its output is

5 - HELLO
4 - ELLO
3 - LLO
2 - LO
1 - O

As for your example then in this statement

printf("%lu\n",strlen(p+sizeof(p)-sizeof(x)+5) );

the expression p + sizeof( p ) has the type char * that is the expression yields a pointer that points one past the last element of the array object p.

The expression p + sizeof( p ) - sizeof( x ) moves the pointer to the left (it seems that sizeof( x ) is equal to 8 in your system). And the expression p + sizeof( p ) - sizeof( x ) + 5 moves the pointer to the right.

As result the whole expression yields a pointer that pointes to the following place in the character array p

char p[]="CALIFORNIA\n";
                   ^
                   |

Thus the length of the string that looks like "A\n" is equal to 2.