Facebook
From Red Pelican, 1 Year ago, written in Plain Text.
This paste is a reply to Untitled from Chunky Giraffe - view diff
Embed
Download Paste or View Raw
Hits: 155
  1. #include <stdio.h>
  2. #include <assert.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. struct Person {
  6.  char *name;
  7.  int age;
  8.  int height;
  9.  int weight;
  10. };
  11. struct Person *Person_create(char *name, int age, int height, int weight)
  12. {
  13.  struct Person *who = malloc(sizeof(struct Person));
  14.  assert(who != NULL);
  15.  who->name = strdup(name);
  16.  who->age = age;
  17.  who->height = height;
  18.  who->weight = weight;
  19.  return who;
  20. }
  21. void Person_destroy(struct Person *who)
  22. {
  23.  assert(who != NULL);
  24.  free(who->name);
  25.  free(who);
  26. }
  27. void Person_print(struct Person *who)
  28. {
  29.  printf("Name: %s\n", who->name);
  30.  printf("\tAge: %d\n", who->age);
  31.  printf("\tHeight: %d\n", who->height);
  32.  printf("\tWeight: %d\n", who->weight);
  33. }
  34. int main(int argc, char *argv[])
  35. {
  36.  // make two people structures
  37.  struct Person *joe = Person_create(
  38.  "Joe Alex", 32, 64, 140);
  39.  struct Person *frank = Person_create(
  40.  struct Person *frank = Person_create(
  41.  "Frank Blank", 20, 72, 180);
  42.  // print them out and where they are in memory
  43.  printf("Joe is at memory location %p:\n", joe);
  44.  Person_print(joe);
  45.  printf("Frank is at memory location %p:\n", frank);
  46.  Person_print(frank);
  47.  // make everyone age 20 years and print them again
  48.  joe->age += 20;
  49.  joe->height -= 2;
  50.  joe->weight += 40;
  51.  Person_print(joe);
  52.  frank->age += 20;
  53.  frank->weight += 20;
  54.  Person_print(frank);
  55.  // destroy them both so we clean up
  56.  Person_destroy(joe);
  57.  Person_destroy(frank);
  58.  return 0;
  59. }
  60.