Ok just created this and have only done some real limited testing on it.
This was actually one time I wish'd for the C++ classes.
Would like to hear if anyone sees anything alarmily wrong with it. I haven't taken the time to try to optimise it yet but I will tomorrow
Thanks
Warning: 75 line program
Code:
#include <stdio.h>
#include <stdlib.h>
/* type define the stack */
typedef struct {
void *ptr;
void *lower;
void *upper;
}Stack;
int stack_init(Stack *, size_t);
int push(Stack *, void *, size_t);
int pop(Stack *, void *, size_t);
int stack_destroy(Stack *);
int main(void){
Stack stack;
int x;
if ( !stack_init(&stack, 100) ) {
perror("Problem with initalizing the stack");
return 1;
}
x = 5;
printf("1) %d\n", x);
push (&stack, &x, sizeof x);
x = 100;
printf("2) %d\n", x);
pop (&stack, &x, sizeof x);
printf("3) %d\n", x);
if ( !stack_destroy(&stack) ) {
perror("problem with destroying the stack");
}
return 0;
}
int stack_init(Stack *stack, size_t size){
stack->lower = calloc (1, size);
if ( stack->lower == NULL )
return 0;
stack->ptr = stack->upper = stack->ptr + size;
return 1;
}
int stack_destroy(Stack *stack){
if ( stack->lower == NULL)
return 0;
free(stack->lower);
stack->lower = stack->ptr = stack->upper = NULL;
return 1;
}
int push (Stack *stack, void *var, size_t size){
int count;
if ( !((stack->ptr - size) > stack->lower) )
return 0;
stack->ptr -= size;
for ( count=0; count<size; count++)
*(char *)((stack->ptr)+count) = *(char *)(var+count);
return 1;
}
int pop ( Stack *stack, void *var, size_t size)
{
int count;
if ( ! ( (stack->ptr+size) <= stack->upper) )
return 0;
for ( count=0; count<size; count++)
*(char *)(var+count) = *(char *)((stack->ptr)+count);
stack->ptr += size;
return 1;
}