sugaray said:
hi, it just came up my mind that since we can get the length of any
given string literal S with 'sizeof S-1', so, what's the merit of
library function strlen()'s existence ? thanx in advance for your
instruction.
You are very confused. Consider the following program. Does 'sizeof'
help in any way in determining the length of the string?
#include <stdio.h>
#include <string.h>
int main(void)
{
char foo[BUFSIZ] = "crap";
char *bar = foo;
printf("When bar points to foo containing \"%s\",\n"
" sizeof foo = %lu, strlen(foo) = %lu\n"
" sizeof bar = %lu, strlen(bar) = %lu\n\n",
foo,
(unsigned long) sizeof foo, (unsigned long) strlen(foo),
(unsigned long) sizeof bar, (unsigned long) strlen(bar));
strcpy(foo, "bananas");
printf("When bar points to foo containing \"%s\",\n"
" sizeof foo = %lu, strlen(foo) = %lu\n"
" sizeof bar = %lu, strlen(bar) = %lu\n\n",
foo,
(unsigned long) sizeof foo, (unsigned long) strlen(foo),
(unsigned long) sizeof bar, (unsigned long) strlen(bar));
return 0;
}
When bar points to foo containing "crap",
sizeof foo = 16384, strlen(foo) = 4
sizeof bar = 4, strlen(bar) = 4
When bar points to foo containing "bananas",
sizeof foo = 16384, strlen(foo) = 7
sizeof bar = 4, strlen(bar) = 7