Home > Blockchain >  Wrong strlen returning char Matrix
Wrong strlen returning char Matrix

Time:01-13

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).

CodePudding user response:

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

CodePudding user response:

//1
char t[2][6];
memcpy(t[0], "  *  ", 6);
memcpy(t[1], "  *  ", 6);

//2
char* tt[2] = { "  *  ","  *  " };

//3
char ttt[2][6] = { ' ',' ','*',' ',' ',0,' ',' ','*',' ',' ',0 };

//4
char (*tttt)[6] = (char(*)[6]) "  *  " "  *  ";
  • Related