Browse Source

added another example of extending a structure with nested anon. structs, nested in a anon. union for direct access of the nested struct

master
T. Meissner 10 years ago
parent
commit
523e4b2aec
2 changed files with 44 additions and 9 deletions
  1. +6
    -9
      21st_century_c/chapter11/Makefile
  2. +38
    -0
      21st_century_c/chapter11/seamlesstwo.c

+ 6
- 9
21st_century_c/chapter11/Makefile View File

@ -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

+ 38
- 0
21st_century_c/chapter11/seamlesstwo.c View File

@ -0,0 +1,38 @@
#include <stdio.h>
#include <math.h>
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);
}

Loading…
Cancel
Save