/* This program tries to demonstrate two different types of dynamic * memory allocation using strings. */ #include #include typedef struct node { char * string; struct node *next; } Node; /* Insert the new string into the node. Use only as much space as needed. Treat the linked list like a stack. Note the address of * the pointer to the linked list has been passed in as a parameter. This allows it's value to change as required -- it also means * that it must be dereferenced when used. */ void insert( Node ** head, char * new_string ) { Node * ptr; ptr = (Node *) malloc ( sizeof(Node) ); if ( ptr == NULL ) { fprintf(stderr,"Error! Could not allocate space\n"); exit(-2); } /* if */ ptr->next = *head; /* One extra space, for the '\0' character implicit in strings, is required. */ ptr->string = (char *) malloc(sizeof(char)*(strlen(new_string)+1)); strcpy( ptr->string, new_string ); *head = ptr; } /* insert */ int main( void ) { char buffer[20]; Node * root = NULL, *tmp; printf("Enter a list of words, each under 20 characters in length.\n"); printf("Press -d to signal EOF\n"); for (;;) { if ( scanf("%s", buffer) == EOF ) break; insert(&root, buffer); /* Note that "&root" and not "root" was passed in. */ } /* for */ printf("The list was, in reverse order:\n"); for ( tmp = root; tmp != NULL; tmp = tmp->next ) { printf("%s\n", tmp->string); free( tmp->string ); free( root ); root = tmp->next; } /* for */ }