home *** CD-ROM | disk | FTP | other *** search
/ Shareware Overload / ShartewareOverload.cdr / progm / ctutor2.zip / DYNLIST.C < prev    next >
Text File  |  1989-11-10  |  2KB  |  58 lines

  1.                                          /* Chapter 12 - Program 1 */
  2. #include "stdio.h"
  3. #include "string.h"
  4. #include "stdlib.h"
  5.  
  6. void main()
  7. {
  8. struct animal {
  9.    char name[25];
  10.    char breed[25];
  11.    int age;
  12. } *pet1, *pet2, *pet3;
  13.  
  14.    pet1 = (struct animal *)malloc(sizeof(struct animal));
  15.    strcpy(pet1->name,"General");
  16.    strcpy(pet1->breed,"Mixed Breed");
  17.    pet1->age = 1;
  18.  
  19.    pet2 = pet1;   /* pet2 now points to the above data structure */
  20.  
  21.    pet1 = (struct animal *)malloc(sizeof(struct animal));
  22.    strcpy(pet1->name,"Frank");
  23.    strcpy(pet1->breed,"Labrador Retriever");
  24.    pet1->age = 3;
  25.  
  26.    pet3 = (struct animal *)malloc(sizeof(struct animal));
  27.    strcpy(pet3->name,"Krystal");
  28.    strcpy(pet3->breed,"German Shepherd");
  29.    pet3->age = 4;
  30.  
  31.        /* now print out the data described above */
  32.  
  33.    printf("%s is a %s, and is %d years old.\n", pet1->name,
  34.            pet1->breed, pet1->age);
  35.  
  36.    printf("%s is a %s, and is %d years old.\n", pet2->name,
  37.            pet2->breed, pet2->age);
  38.  
  39.    printf("%s is a %s, and is %d years old.\n", pet3->name,
  40.            pet3->breed, pet3->age);
  41.  
  42.    pet1 = pet3;   /* pet1 now points to the same structure that
  43.                       pet3 points to                           */
  44.    free(pet3);    /* this frees up one structure               */
  45.    free(pet2);    /* this frees up one more structure          */
  46. /* free(pet1);    this cannot be done, see explanation in text */
  47. }
  48.  
  49.  
  50.  
  51. /* Result of execution
  52.  
  53. Frank is a Laborador Retriever, and is 3 years old.
  54. General is a Mixed Breed, and is 1 years old.
  55. Krystal is a German Shepherd, and is 4 years old.
  56.  
  57. */
  58.