/* --------------------------------------------------------------------- ** Implementation of a dynamic ragged array. ** Figure 19.3: A variable number of varying-sized objects. ** Figure 19.4: Building a ragged array. ** --------------------------------------------------------------------- */ #include "tools.h" typedef struct FAMILY { int n; string* name; } family_t; void get_names( string* new, int mem ); void print_family( family_t f); void main( void ) { int mem; /* # of members in new family. */ string* new; /* Newest family. */ int fam = 0; /* # of families in the club. */ family_t club[20]; /* Membership roster. */ puts( "\n Pleasant Lakes Club Membership List " ); /*fam = read_file( club ); /* Read current members from file. */ /*print_all( club, fam ); /* Print roster of current members. */ printf( " Ready for new family data. How many people? " ); scanf( "%i", &mem ); new = malloc( mem * sizeof(string) ); if (new == NULL) fatal( "Not enough memory for new family." ); club[fam].n = mem; club[fam].name = new; get_names( new, mem ); print_family( club[fam] ); fam++; //write_file( club, fam ); /* Will write file and free dynamic storage. */ bye(); } /* ------------------------------------------------------------------------ */ void get_names( string new[], int mem ) { int k; /* Loop index. */ char buf[80]; /* For input of member names. */ int len; /* Name length. */ puts( "\n Enter names at prompt, parents first.\n" " Surnames may be omitted if same as first." ); for (k = 0; k < mem; ++k) { /* Read & install new names. */ printf( " > " ); scanf( " %79[^\n]", buf ); len = strlen( buf ); /* Measure name. */ new[k] = malloc( len + 1 ); /* Allocate space. */ strcpy( new[k], buf ); /* Copy name into space. */ } } /* ------------------------------------------------------------------------ */ void print_family( family_t f ) { int k; /* subscript variable for loop */ printf( "\n This family has %i members:\n", f.n ); for (k = 0; k < f.n; ++k) printf( "\t%s\n", f.name[k] ); }