Bill Cunningham wrote:
>You are not making any sense. Are you asking why strlen exists? It
should be obvious, even to you. How else do you find the length of a
zero terminated string?
C must not count '\0' as being part of a string.
It is a part of a C string. However it is not counted by strlen.
This is the simple code I tried,
int main(void) {
size_t t;
char hello[]="hello world\n";
t=strlen(hello) ;
printf("%i",hel lo);
The format for size_t is %zu. If your compiler does not support this
then the next best method is to use %lu and cast it's argument to
unsigned long.
}
The integer returned was 12. When I removed the '\n' from the
string and recompiled 11 was the number returned.
Yes. So?
Why in production code would someone want to know the length of a
string? That's what I am asking. Hence my inexperience speaks for
itself.
Not all situations are such that we can know the length of a string at
compile time, as in your example above. Often strings are constructed
at runtime, received from external files or the user and many programs
do quite a lot of string processing, like splitting, concatenating,
etc. Also even if your code knows the lengths of your strings, other
library code will not. One way for them to act sanely upon your strings
is to use strlen to get their length, or watch out for the null
character as they process it.
For example in the program:
int main(int argc, char **argv) {
/* ... */
}
if the program is given any command line parameters, then there is no
way for the program to find out their lengths other than by using
strlen (or equivalent inline code).
So strlen is necessary with C strings because they don't carry their
length with them. However good programs try to minimise the use of
strlen by caching previous results and storing the lengths of known
strings, instead of discarding the information and recomputing it every
here and there.