S04 Answer


/* Puzzle S04 -- string length*/

#include <stdio.h>
#include <stdlib.h>

int strlength( char *p )
{
  int length = 0;
  while ( *p++ ) length++ ;
  return length;
}

int main(int argc, char *argv[])
{
  char *trials[] = {"String of length 19", "X", "", "Yet another string",
                    "End of\nlines should\nwork fine."};
  int j, ch;

  for ( j=0; j<sizeof(trials)/sizeof(char *); j++ )
  {
    printf("%s\nis length %d\n\n", trials[j], strlength( trials[j] ) );
  }

  system("PAUSE");
  return 0;
}

Comments: You might be happier with a wordier, but equivalent, version of the function:

int strlength( char *p)
{
  int length=0;
  
  while ( *p != '\0' )
  {
    length++ ;
	 p++ ;
  }
  
  return length;
}

The less wordy version makes use of the fact that C regards NUL as false, and anything else as true. It also makes use of how the postfix autoincrement operator increments the variable only after the value in the variable has been used in the expression.

For extra fun, write a recursive version of the function (although in practice nobody would actually write it that way.)