From c0d7a5ab3992064a63576e0acd306526da2a8c0f Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Wed, 13 Apr 2016 00:02:54 -0400 Subject: [PATCH] ex15 --- lcthw-remnants-2/.gitignore | 1 + lcthw-remnants-2/ex15.c | 54 +++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 lcthw-remnants-2/ex15.c diff --git a/lcthw-remnants-2/.gitignore b/lcthw-remnants-2/.gitignore index 45cf7ff..45e799c 100644 --- a/lcthw-remnants-2/.gitignore +++ b/lcthw-remnants-2/.gitignore @@ -12,3 +12,4 @@ ex11 ex12 ex13 ex14 +ex15 diff --git a/lcthw-remnants-2/ex15.c b/lcthw-remnants-2/ex15.c new file mode 100644 index 0000000..39f7554 --- /dev/null +++ b/lcthw-remnants-2/ex15.c @@ -0,0 +1,54 @@ +#include + +int main(int argc, char *argv[]) +{ + // create two arrays we care about + int ages[] = {23, 43, 12, 89, 2}; + char *names[] = { + "Alan", "Frank", + "Mary", "John", "Lisa" + }; + + // safely get the size of ages + int count = sizeof(ages) / sizeof(int); + int i = 0; + + // first way using indexing + for(i = 0; i < count; i++) { + printf("%s has %d years alive.\n", + names[i], ages[i]); + } + + printf("---\n"); + + // setup the pointers to the start of the arrays + int *cur_age = ages; + char **cur_name = names; + + // second way using pointers + for(i = 0; i < count; i++) { + printf("%s is %d years old.\n", + *(cur_name+i), *(cur_age+i)); + } + + printf("---\n"); + + // third way, pointers are just arrays + for(i = 0; i < count; i++) { + printf("%s is %d years old again.\n", + cur_name[i], cur_age[i]); + } + + printf("---\n"); + + // fourth way with pointers in a stupid complex way + for(cur_name = names, cur_age = ages; + (cur_age - ages) < count; + cur_name++, cur_age++) + { + printf("%s lived %d years so far.\n", + *cur_name, *cur_age); + } + + return 0; +}