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

  1.  /* Demonstrates the use of malloc() to allocate storage */
  2.  /* space for string data. */
  3.  
  4.  #include <stdio.h>
  5.  #include <stdlib.h>
  6.  
  7.  char count, *ptr, *p;
  8.  
  9.  main()
  10.  {
  11.     /* Allocate a block of 35 bytes. Test for success. */
  12.     /* The exit() library function terminates the program. */
  13.  
  14.     ptr = malloc(35 * sizeof(char));
  15.  
  16.     if ( ptr == NULL )
  17.     {
  18.         puts("Memory allocation error.");
  19.         exit(1);
  20.     }
  21.  
  22.     /* Fill the string with values 65 through 90, */
  23.     /* which are the ASCII codes for A-Z. */
  24.  
  25.     /* p is a pointer used to step through the string. */
  26.     /* You want ptr to remain pointed at the start */
  27.     /* of the string. */
  28.  
  29.     p = ptr;
  30.  
  31.     for (count = 65; count < 91 ; count++)
  32.         *p++ = count;
  33.  
  34.     /* Add the terminating null character. */
  35.  
  36.     *p = '\0';
  37.  
  38.     /* Display the string on the screen. */
  39.  
  40.     puts(ptr);
  41.  }
  42.