From 224300e1cf146572e16a776745bc3dd79e716ec1 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Fri, 19 Apr 2024 21:51:42 -0400 Subject: [PATCH] Up through lcthw ex 15 --- lcthw/.gitignore | 12 ++---------- lcthw/Makefile | 8 ++++---- lcthw/ex15.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 14 deletions(-) create mode 100644 lcthw/ex15.c diff --git a/lcthw/.gitignore b/lcthw/.gitignore index 8942676..9b8cce7 100644 --- a/lcthw/.gitignore +++ b/lcthw/.gitignore @@ -1,10 +1,2 @@ -ex1 -ex3 -ex7 -ex8 -ex9 -ex10 -ex11 -ex12 -ex13 -ex14 +ex* +!ex*.c diff --git a/lcthw/Makefile b/lcthw/Makefile index 7e2b449..e7819b5 100644 --- a/lcthw/Makefile +++ b/lcthw/Makefile @@ -19,17 +19,17 @@ clean: build: $(BUILD_TARGETS) .PHONY: gtest -gtest: +gtest: $(BUILD_TARGETS) @$(foreach bt, $(BUILD_TARGETS), make .gtest.$(bt) &&) printf '\ngYAY\n' -.gtest.%: +.gtest.%: % @if test -f .$*.argv; then readarray -t test_argv <.$*.argv; fi && \ printf '\n==> %s\n' "$*" && $(GDBRUN) ./$* "$${test_argv[@]}" .PHONY: test -test: +test: $(BUILD_TARGETS) @$(foreach bt, $(BUILD_TARGETS), make .test.$(bt) &&) printf '\nYAY\n' -.test.%: +.test.%: % @if test -f .$*.argv; then readarray -t test_argv <.$*.argv; fi && \ printf '\n==> %s\n' "$*" && ./$* "$${test_argv[@]}" diff --git a/lcthw/ex15.c b/lcthw/ex15.c new file mode 100644 index 0000000..2a45c30 --- /dev/null +++ b/lcthw/ex15.c @@ -0,0 +1,48 @@ +#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; +}