home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tyc / list20_3.c < prev    next >
C/C++ Source or Header  |  1993-10-16  |  799b  |  39 lines

  1.  /* Using realloc() to change memory allocation. */
  2.  
  3.  #include <stdio.h>
  4.  #include <stdlib.h>
  5.  #include <string.h>
  6.  
  7.  main()
  8.  {
  9.      char buf[80], *message;
  10.  
  11.      /* Input a string. */
  12.  
  13.      puts("Enter a line of text.");
  14.      gets(buf);
  15.  
  16.      /* Allocate the initial block and copy the string to it. */
  17.  
  18.      message = realloc(NULL, strlen(buf)+1);
  19.      strcpy(message, buf);
  20.  
  21.      /* Display the message. */
  22.  
  23.      puts(message);
  24.  
  25.      /* Get another string from the user. */
  26.  
  27.      puts("Enter another line of text.");
  28.      gets(buf);
  29.  
  30.      /* Increase the allocation then concatenate the string to it. */
  31.  
  32.      message = realloc(message, (strlen(message)+strlen(buf)+1));
  33.      strcat(message, buf);
  34.  
  35.      /* Display the new message. */
  36.  
  37.      puts(message);
  38.  }
  39.