home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / qc_prog / chap08 / reverse.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-04-05  |  1.2 KB  |  54 lines

  1. /* reverse.c -- demonstrates an array of pointers     */
  2. /*              by reversing lines of text            */
  3.  
  4. #include <stdio.h>         /* for NULL   */
  5. #include <malloc.h>        /* for size_t */
  6.  
  7. #define MAXL 20
  8.  
  9. main()
  10. {
  11.     char *cptrs[MAXL];     /* array of pointers */
  12.     char *cp;
  13.     int count, i, j, ch;
  14.     extern char *Getbyte();
  15.  
  16.  
  17.     printf("Type in several lines of text, and I will\n");
  18.     printf("print them back out in reverse order.\n");
  19.     printf("(Any blank line ends input):\n");
  20.  
  21.     for (i = 0; i < MAXL; ++i)
  22.         {
  23.         cp = Getbyte();
  24.         cptrs[i] = cp;     /* assign address to pointer */
  25.         count = 0;
  26.         while ((ch = getchar()) != '\n') /* gather line */
  27.             {
  28.             *cp = ch;
  29.             cp = Getbyte();
  30.             ++count;
  31.             }
  32.         *cp = '\0';
  33.         if (count == 0)    /* all done if blank line */
  34.             break;
  35.         }
  36.     printf("---------<reversed>---------\n");
  37.     for (j = i-1; j >= 0; --j)
  38.         {
  39.         printf("%s\n", cptrs[j]);
  40.         }
  41. }
  42.  
  43. char *Getbyte(void)
  44. {
  45.     char *cp;
  46.  
  47.     if ((cp = sbrk(1)) == (char *)-1)
  48.         {
  49.         printf("Panic: sbrk failed\n");
  50.         exit(1);
  51.         }
  52.     return (cp);
  53. }
  54.