home *** CD-ROM | disk | FTP | other *** search
/ C by Discovery (4th Edition) / C_By_Discovery_4th_Edition.tar / C_By_Discovery_4th_Edition / _DISK_ / ch11 / malloc.c < prev    next >
C/C++ Source or Header  |  2005-06-16  |  2KB  |  44 lines

  1. /*               malloc.c
  2.  *
  3.  *   Synopsis  - Accepts input of a line of text, separates each 
  4.  *               of the blank-separated words in the line, and
  5.  *               displays each word.
  6.  *
  7.  *   Objective - To illustrate use of the malloc() function.
  8.  */
  9.  
  10. /* Include Files */
  11. #include <stdio.h>
  12. #include <stdlib.h>                                     /* Note 1 */
  13. #include <string.h>
  14.  
  15. /* Constant Definitions */
  16. #define BUF_SIZE  512
  17.  
  18. int main( void )
  19. {
  20.      char instring[BUF_SIZE], *currentpl, *endword, *word;
  21.  
  22.      printf( "Enter a line of text " );
  23.      printf( "with words separated with blanks:\n" );
  24.  
  25.      fgets( instring, BUF_SIZE, stdin );
  26.      instring[ strlen( instring ) - 1 ] = '\0';
  27.      currentpl = instring;
  28.                                                         /* Note 2 */
  29.      while (( endword = strchr( currentpl, ' ' )) != NULL ) {
  30.           *endword = '\0';                              /* Note 3 */
  31.                                                         /* Note 4 */
  32.           word = ( char * ) malloc( strlen( currentpl ) + 1 );
  33.           strcpy( word, currentpl );
  34.           printf( "I read that as \"%s\".\n", word );
  35.           currentpl = endword+1;                        /* Note 5 */
  36.           free (( void * ) word );                      /* Note 6 */
  37.      }
  38.                                                         /* Note 7 */
  39.      word = ( char * )malloc( strlen( currentpl ) + 1 );
  40.      strcpy( word, currentpl );
  41.      printf( "I read that as \"%s\".\n", word );
  42.      free(( void * ) word );
  43.      return 0;
  44. }