From 3d55ee97415f52128b0858d49ed82d6761acc738 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Wed, 13 Apr 2016 00:16:17 -0400 Subject: [PATCH] ex16 --- lcthw-remnants-2/.gitignore | 1 + lcthw-remnants-2/ex16.c | 73 +++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 lcthw-remnants-2/ex16.c diff --git a/lcthw-remnants-2/.gitignore b/lcthw-remnants-2/.gitignore index 45e799c..83cb010 100644 --- a/lcthw-remnants-2/.gitignore +++ b/lcthw-remnants-2/.gitignore @@ -13,3 +13,4 @@ ex12 ex13 ex14 ex15 +ex16 diff --git a/lcthw-remnants-2/ex16.c b/lcthw-remnants-2/ex16.c new file mode 100644 index 0000000..775c683 --- /dev/null +++ b/lcthw-remnants-2/ex16.c @@ -0,0 +1,73 @@ +#include +#include +#include +#include + +struct Person { + char *name; + int age; + int height; + int weight; +}; + +struct Person *Person_create(char *name, int age, int height, int weight) +{ + struct Person *who = malloc(sizeof(struct Person)); + assert(who != NULL); + + who->name = strdup(name); + who->age = age; + who->height = height; + who->weight = weight; + + return who; +} + +void Person_destroy(struct Person *who) +{ + assert(who != NULL); + + free(who->name); + free(who); +} + +void Person_print(struct Person *who) +{ + printf("Name: %s\n", who->name); + printf("\tAge: %d\n", who->age); + printf("\tHeight: %d\n", who->height); + printf("\tWeight: %d\n", who->weight); +} + +int main(int argc, char *argv[]) +{ + // make two people structures + struct Person *joe = Person_create( + "Joe Alex", 32, 64, 140); + + struct Person *frank = Person_create( + "Frank Blank", 20, 72, 180); + + // print them out and where they are in memory + printf("Joe is at memory location %p:\n", joe); + Person_print(joe); + + printf("Frank is at memory location %p:\n", frank); + Person_print(frank); + + // make everyone age 20 years and print them again + joe->age += 20; + joe->height -= 2; + joe->weight += 40; + Person_print(joe); + + frank->age += 20; + frank->weight += 20; + Person_print(frank); + + // destroy them both so we clean up + Person_destroy(joe); + Person_destroy(frank); + + return 0; +}