/* Program to reverse a list of names using the stack package */ #include #include #include #include "stack.h" void fatal(char message[]); int can_load_name(stack stk); void unload_name(stack stk); main() { stack s; /* Declare stack variable */ s = stack_init(100); /* Initialise */ if (s == NULL) { fatal("Cannot initialise stack"); } printf("Enter names:\n"); while (can_load_name(s)) { /* Try to load another name */ /* Try again */ } printf("Names are:\n"); /* Here all names are loaded into stack; now unload and output. */ while (! stack_empty(s)) { /* Still more in stack? */ unload_name(s); /* yes - pop and print */ } stack_free(s); /* Not necessary in this program, but good practice to free any memory not required further. */ return 0; } /* fatal: print error and stop */ void fatal(char message[]) { fprintf(stderr, "ERROR:%s!\n", message); exit(EXIT_FAILURE); } /* can_load_name: Read a name & push; return 1 (success), or 0 (fail) */ int can_load_name(stack s) { char buf[80], *nam; /* Temporary buffer, and pointer for the name */ if (scanf("%79[^\n]%*[^\n]", buf) < 1) { /* Try to read name. Fail? */ return 0; /* Report failure */ } getchar(); /* Input '\n', ready for next name input */ nam = (char*)malloc((strlen(buf)+1) * sizeof(char)); /* get space */ if (nam == NULL) { /* fail? */ fatal("No space for name"); } strcpy(nam, buf); /* copy string into nam */ if (! stack_push(s, nam)) { /* Try pushing buffer's address - fail? */ fatal("No room on stack"); } return 1; /* Report success */ } /* unload_name: Assumes there is a name in the stack; removes & prints it */ void unload_name(stack stk) { char * buf; buf = (char*)stack_pop(stk); printf("%s\n", buf); free(buf); /* Reclaim space malloc'ed above. */ }