/* p22.c */ /* Managing lists of structures */ #include #include #include struct sphere_t { struct sphere_t *next; double center[3]; /* x, y, z */ double radius; }; struct list_t { struct sphere_t *head; struct sphere_t *tail; }; /* Initialize a list structure */ struct list_t *list_init(void) { struct list_t *list; list = (struct list_t *)malloc(sizeof(struct list_t)); list->head = NULL; list->tail = NULL; } /* Append sphere structure to end of list */ void list_add( struct list_t *list, struct sphere_t *new) { if (list->head == NULL) { list->head = new; list->tail = new; } else { list->tail->next = new; list->tail = new; } } /* Allocate a new sphere structure */ /* and read in attributes */ struct sphere_t *sphere_load( FILE *in) { double x, y, z; double r; struct sphere_t *new; if (fscanf(in, "%lf %lf %lf %lf", &x, &y, &z, &r) == 4) { new = malloc(sizeof(struct sphere_t)); new->center[0] = x; new->center[1] = y; new->center[2] = z; new->radius = r; new->next = NULL; return(new); } return(0); } void sphere_print( FILE *where, struct sphere_t *sphere) { fprintf(where, "Radius = %6.2lf \n", sphere->radius); fprintf(where, "Center = (%6.2lf, %6.2lf, %6.2lf)\n", sphere->center[0], sphere->center[1], sphere->center[2]); } main() { double x, y, z; double r; struct sphere_t *sphere; struct list_t *list; /* Allocate and initialize the list structure */ list = list_init(); /* Load sphere descriptions until end of file */ while (sphere = sphere_load(stdin)) { list_add(list, sphere); } /* Print the sphere descriptions */ sphere = list->head; while (sphere) { sphere_print(stderr, sphere); sphere = sphere->next; } }