Search code examples
cstringstrlen

Why C function strlen() returns a wrong length of a char?


My C codes are listed below:

char s="MIDSH"[3];
printf("%d\n",strlen(&s));

The result of running is 2, which is wrong because char s is just an 'S'.

Does anybody know why and how to solve this problem?


Solution

  • That's actually quite an interesting question. Let's break it up:

    "MIDSH"[3]
    

    String literals have array types. So the above applies the subscript operator to the array and evaluates to the 4th character 'S'. It then assigns it to the single character variable s.

    printf("%d\n",strlen(&s));
    

    Since s is a single character, and not part of an actual string, the behavior is undefined for the above code.