From 523e4b2aecfe26876a697850c1cf1330128098d5 Mon Sep 17 00:00:00 2001 From: tmeissner Date: Fri, 15 May 2015 21:54:00 +0200 Subject: [PATCH] added another example of extending a structure with nested anon. structs, nested in a anon. union for direct access of the nested struct --- 21st_century_c/chapter11/Makefile | 15 ++++------ 21st_century_c/chapter11/seamlesstwo.c | 38 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 9 deletions(-) create mode 100644 21st_century_c/chapter11/seamlesstwo.c diff --git a/21st_century_c/chapter11/Makefile b/21st_century_c/chapter11/Makefile index 1087630..74dfa6c 100644 --- a/21st_century_c/chapter11/Makefile +++ b/21st_century_c/chapter11/Makefile @@ -1,20 +1,18 @@ CFLAGS = -Wall -O3 --std=c11 -boxes : boxes.c - $(CC) $(CFLAGS) $@.c -o $@ - -show_tree : process_dir.h process_dir.c show_tree.c - $(CC) $(CFLAGS) process_dir.c $@.c -o $@ - simple_cplx : cplx.h complex.c simple_cplx.c $(CC) `pkg-config --cflags --libs gsl` $(CFLAGS) complex.c $@.c -o $@ seamlessone : seamlessone.c $(CC) $(CFLAGS) -fms-extensions -Wno-microsoft $@.c -o $@ +seamlesstwo : seamlesstwo.c + $(CC) $(CFLAGS) -fms-extensions -Wno-microsoft $@.c -o $@ + + .PHONY : all -all : boxes show_tree simple_cplx +all : simple_cplx seamlessone seamlesstwo .PHONY : check check : *.h *.c @@ -22,8 +20,7 @@ check : *.h *.c .PHONY : clean clean : - rm -f boxes - rm -f show_tree rm -f simple_cplx rm -f seamlessone + rm -f seamlesstwo rm -rf *.dSYM diff --git a/21st_century_c/chapter11/seamlesstwo.c b/21st_century_c/chapter11/seamlesstwo.c new file mode 100644 index 0000000..d5c9b1a --- /dev/null +++ b/21st_century_c/chapter11/seamlesstwo.c @@ -0,0 +1,38 @@ +#include +#include + + + +typedef struct point { + double x, y; +} point; + + + +typedef struct { + union { + struct point; + point p2; + }; + double z; +} threepoint; + + +double length(point p) { + return sqrt(p.x * p.x + p.y * p.y); +} + +double threelength(threepoint p) { + return sqrt(p.x * p.x + p.y * p.y + p.z * p.z); +} + + +int main() { + + threepoint p = {.x = 3, .y = 0, .z = 4}; + printf("p is %g units from the origin\n", threelength(p)); + + double xylength = length(p.p2); + printf("Its projection onto the XY plane is %g units from the origin\n", xylength); + +} \ No newline at end of file