#include #include #include /* contacts - growable -- shows how to use malloc and realloc to grow an array */ #define NAME_LEN 100 #define NUM_LEN 30 #define INIT_CAP 4 #define ADDN_AMT 2 struct contact { char name[NAME_LEN]; char phonenum[NUM_LEN]; }; void fill_entry(struct contact *); void print_entry(struct contact *); void list_contacts(struct contact *, int); int find_contact(struct contact *, int); int add_to_list( struct contact **, int, int ); struct contact *expand_list( struct contact * , int *capacity ); int main() { struct contact *contact_list ; // will point to an array int capacity = INIT_CAP; int n_rows = 0; char choice[NAME_LEN]; contact_list = malloc( INIT_CAP * sizeof( struct contact ) ); while( 1 ) { printf("add, find, list? "); fgets( choice, NAME_LEN, stdin); switch ( choice[0] ) { case 'a': capacity = add_to_list( &contact_list, n_rows, capacity); n_rows++; break; case 'f': find_contact( contact_list, n_rows ); break; case 'l': list_contacts( contact_list, n_rows ); break; case 'q': return 0; default: printf("unknown choice: \"%s\"\n", choice); } } } int add_to_list( struct contact **list_addr , int num_so_far, int capacity ) { struct contact *list = *list_addr; if ( num_so_far >= capacity ){ list = expand_list( list, &capacity ); *list_addr = list; } fill_entry(&list[num_so_far]); // &alan is ADDRESS of the variable return capacity; } // expand the array and update by ref the capacity // ret new list struct contact *expand_list( struct contact *orig, int *cap_ptr) { struct contact *new_list = realloc( orig, *cap_ptr + ADDN_AMT ) ; *cap_ptr += ADDN_AMT; return new_list; } // search list for a name // linear search and stop at found or at end // ret 1 if found, 0 if not int find_contact( struct contact *contact_list, int n_rows ) { int i; char findme[NAME_LEN]; printf("Find what name? "); scanf("%s", findme); for ( i = 0 ; i < n_rows ; i++ ) { if ( strcmp(contact_list[i].name , findme) == 0 ) { print_entry( &contact_list[i] ); return 1; } } return 0; } // iterate and print void list_contacts( struct contact *contact_list, int n_rows ) { int i; for ( i = 0 ; i < n_rows ; i++ ) print_entry( &contact_list[i] ); } void fill_entry( struct contact *cp ) { printf("name? "); scanf("%s", cp->name ); printf("phone num? "); scanf("%s", cp->phonenum ); } void print_entry( struct contact *cp ) { printf("name: %s\n", cp->name); printf("phone num: %s\n", cp->phonenum); }