/* * Program to compute length of strings various ways, as a silly * example of working with strings. */ #include /* compute length using array and indices */ int strlen_array(char s[]) { int count = 0; while (s[count] != '\0') ++count; return count; } /* compute length using pointers */ int strlen_ptr(char *s) { char *p = s; while (*p != '\0') ++p; return p-s; } /* compute length using pointers and recursion */ int strlen_recur(char *s) { if (*s == '\0') return 0; return 1 + strlen_recur(s+1); } /* try various functions, printing input and outputs */ void tryfcns(char *s) { printf("'%s' %d %d %d\n", s, strlen_array(s), strlen_ptr(s), strlen_recur(s)); } int main(void) { tryfcns("hello"); tryfcns("a somewhat longer string"); return 0; }