S06 Answer


/* Puzzle S06 -- string copy*/

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

void stringCopy( char *copy, char *source )
{
  while ( *source )
  {
    *copy = *source;
    copy++ ; source++ ;
  }
  *copy = '\0' ;
}

int main(int argc, char *argv[])
{
  char buffer[100];
  char *trials[] =
  {
  "The game is afoot!",
  "Genius is an infinite capacity for taking pains.",
  "So is programming.",
  "",
  "As always,\nlinefeeds should\nwork.",
  "Will\ttabs\tconfuse\tthings?",
  "For great fun, change the buffer size to 5!"
  };

  int j ;
  for ( j=0; j<sizeof(trials)/sizeof(char *); j++ )
  {
    stringCopy( buffer, trials[j] );
    printf("%s\n", buffer );
  }

  system("PAUSE");
  return 0;
}

Comments: A shorter version of the function:

void stringCopy( char *copy, char *source )
{
  while ( *copy++ = *source++ ) ;
}

Here, the while loop has no body. The semicolon works as an empty statement. As before, the shorter version makes use of the fact that C regards NUL as false, and anything else as true, and makes use of how the postfix autoincrement operator increments the variable only after the value in the variable has been used in the expression. Also, recall that the value of an entire assignment expression (of an assignment statement) is the value that is assigned to the variable.