1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
#include <stdio.h>
#include <stdlib.h>
/*
This program is written to demonstrate the <stdlib.h> library.
This program will demonstrate memory allocation using malloc.
Written by James M. Rogers
21 March 1999
Released to the Public Domain on this date.
*/
struct element{
struct element *next;
int value;
}element_size;
struct element *initialize () {
struct element *add;
if(add=(struct element *)malloc(sizeof(element_size))){
add->next = (struct element *)NULL;
return add;
} else {
return (struct element *)NULL;
}
}
struct element *push (struct element *top, int value) {
struct element *add;
if (add=(struct element *)malloc(sizeof(element_size))){
add->next=top;
add->value=value;
top=add;
return top;
} else {
printf("Failed to push a value onto the stack, I am quiting.\n");
exit (1);
}
}
struct element *pop (struct element *top, int *value) {
struct element *remove;
fflush(stdout);
*value=top->value;
remove=top;
top=top->next;
free(remove);
return top;
}
main(){
struct element *stack;
int x;
if ( !(stack = initialize())){
printf("Failed to initialize the stack, I am quiting.\n");
exit (1);
}
stack = push(stack, 1);
stack = push(stack, 2);
stack = push(stack, 4);
stack = push(stack, 8);
stack = push(stack, 16);
stack = push(stack, 32);
stack = push(stack, 64);
stack = push(stack, 128);
stack = push(stack, 256);
while (stack = pop(stack, &x)){
printf("Return value is \t%d\n", x);
}
}
|