1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <unistd.h> 5 6 #define LEN 90 7 8 struct basket { 9 char name[LEN]; 10 struct item *item; 11 }; 12 13 struct item { 14 struct item *next; 15 char name[LEN]; 16 }; 17 18 void init_basket( struct basket *b ) { 19 strncpy( b->name, "Basket", LEN ); 20 b->item = NULL; 21 } 22 23 void init_basket_item( struct item *i ) { 24 strncpy( i->name, "", LEN ); 25 i->next = NULL; 26 } 27 28 struct item *last_item( struct basket *b ) { 29 struct item *ptr = NULL; 30 struct item *p = NULL; 31 ptr = b->item; 32 if( ptr == NULL ) { 33 printf( "Returning null\n" ); 34 return( ptr ); 35 } 36 37 while( ptr != NULL ) { 38 p = ptr; 39 ptr = ptr->next; 40 41 } 42 return( p ); 43 } 44 45 struct item *add_item( struct basket *b ) { 46 struct item *ptr,*p; 47 ptr = last_item( b ); 48 p = malloc( sizeof( struct item ) ); 49 init_basket_item( p ); 50 strncpy( p->name, "Created", LEN ); 51 52 /* is this the first item */ 53 if( ptr == NULL ) { 54 printf( "Setting b->item\n" ); 55 b->item = p; 56 } 57 else { 58 ptr->next = p; 59 } 60 return( p ); 61 } 62 63 int main( int argc, char *argv[] ) { 64 struct basket *b = malloc( sizeof( struct basket ) ); 65 struct item *ii;// = malloc( sizeof( struct item ) ); 66 struct item *iii;// = malloc( sizeof( struct item ) ); 67 init_basket( b ); 68 69 ii = add_item( b ); 70 iii = add_item( b ); 71 strncpy( ii->name, "C", LEN ); 72 73 printf( "Basket name: %s\n", b->name ); 74 printf( "Item name: %s\n", b->item->name ); 75 printf( "Item name: %s\n", b->item->next->name ); 76 77 free( b ); 78 return(0); 79 } 80