This might be a bit long question. I was testing some character arrays in C and so came along this code.
char t[10];
strcpy(t, "abcd");
printf("%d\n", strlen(&t[5]));
printf("Length: %d\n", strlen(t));
Now apparently strlen(&t[5])
yields 3 while strlen(t)
returns 4.
I know that string length is 4, this is obvious from inserting four characters. But why does strlen(&t[5])
return 3?
My guess is that
String: a | b | c | d | 0 | 0 | 0 | 0 | 0 | \0
Position: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
strlen(&t[5])
looks at the length of a string composed of positions 6, 7 and 8 (because the 10th character is a NULL terminating character, right)?
OK, then I did some experimentation and modified a code a bit.
char t[10];
strcpy(t, "abcdefghij");
printf("%d\n", strlen(&t[5]));
printf("Length: %d\n", strlen(t));
Now this time strlen(&t[5])
yields 5 while strlen(t)
is 10, as expected. If I understand character arrays correctly, the state should now be
String: a | b | c | d | e | f | g | h | i | j | '\0'
Position: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
so why does strlen(&t[5])
return 5 this time? I've declared a character array of length 10, should then, by the same logic applied above, the result be 4?
Also shouldn't I be running into some compiler errors since the NULL terminating character is actually in the 11th spot? I'm new into C and would very much appreciate anyone's help.