Puzzle S4

Compute the length of a string

[E-4]Write function strlen() that computes the length of a string. The length of a null-terminated string is the number of characters in it, not counting the null at the end. An empty string (one that contains only the null byte) will have a length of zero. Here is a prototype for the function:

int strlength( char *p )

The function's parameter is a pointer to the first byte of the string. Write the function to move the pointer through the successive bytes of the string, incrementing a counter as it does so, until the pointer hits the NUL. Here is a testing program:

/* Puzzle S04 --  string length */
#include <stdio.h>
#include <stdlib.h>

int strlength( char *p )
{
}


int main()
{
  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] ) );
  }
 
  return 0;
}

Note 1: Don't name your function strlen() like the standard function or you may have trouble compiling because of a name conflict.

Note 2: The array trials consists of cells which contain the addresses of string literals. The size of each cell is sizeof(char *) so the number of cells in the array is sizeof(trials)/sizeof(char *).



Previous Page        Answer         Next Page         Home