arrayscstrlen

Wrong strlen returning char Matrix


char t[2][5] = {"  *  ","  *  "};
printf("%d\n",strlen(t[0]));

Output:

11

Why is this happening and how can I print just the length of the first string?

Each string should have a size of 5 (two white spaces plus asterisk plus two whites spaces).


Solution

  • strlen() only works on null-terminated strings, but the strings in your array are not null-terminated. So your code has undefined behavior.

    The string literal " * " has 6 characters, including the null-terminator, but your array only allows space for 5 characters per string, so the null-terminators are getting chopped off.

    Also, strlen() return a size_t rather than an int, so %d is the wrong format specifier to use in printf-style functions when printing a size_t value. You need to use %zu instead.

    Try this:

    char t[2][6] = {"  *  ","  *  "};
    printf("%zu\n", strlen(t[0]));
    

    Online Demo

    Now you will see 5 as expected.

    This would also work, too:

    const char* t[2] = {"  *  ","  *  "};
    printf("%zu\n", strlen(t[0]));
    

    Online Demo