Click on array_stack_without_newstack.c to get source.
/* File: CExamples/OO_pgm_in_C_new/array_stack_without_newstack.c */
#include <stdio.h>
#include <stdlib.h>
#include "stack_with_delete.h"
/* This is the Data Structure used to implement the stack:
array[top-1] is the last element entered, array[0] the first */
typedef struct array_stackstruct
{ int top;
int array[20];
} array_stack, *array_stackptr;
void array_delete_stack( stackptr self )
/* Assumes that sptr is the result of new_stack */
{extern const stack empty_arr_stack; /* forward declare */
if (self != &empty_arr_stack) /* prevent delete of proto-type */
{ free(self->objptr); free(self); }
}/* end delete_stack */
/* The following three functions define the array_stack operations */
int array_isempty(stackptr self)
{return( ((array_stackptr)self->objptr)->top == 0 );
}/* end is_empty */
void array_push(int i, stackptr self)
{array_stackptr asptr;
asptr = (array_stackptr)self->objptr;
/* no check for overflow */
asptr->array[asptr->top++] = i;
}/* end array_push */
int array_pop(stackptr self)
{array_stackptr asptr;
asptr = (array_stackptr)self->objptr;
/* no check for underflow */
return asptr->array[--asptr->top];
}/* end array_pop */
stackptr array_clone (const struct stackstruct* sptr_in) /* note:
cannot use const stackptr as type here */
{stackptr sptr_out;
extern const stack empty_arr_stack; /* forward declare */
if(sptr_in == &empty_arr_stack) printf("\nCloning the proto-type empty_arr_stack\n");
sptr_out = (stackptr)malloc(sizeof(stack));
/* set the function pointers to array functions */
sptr_out->is_empty = array_isempty;
sptr_out->push = array_push;
sptr_out->pop = array_pop;
sptr_out->clone = array_clone;
sptr_out->delete_stack = array_delete_stack;
sptr_out->objptr = (array_stackptr)malloc(sizeof(array_stack));
*((array_stackptr)sptr_out->objptr) = *((array_stackptr)sptr_in->objptr); /* field-wise assign */
return sptr_out;
}/* end array_clone */
static array_stack empty_arr; /* "static" initializes empty_arr.top = 0 */
/* There is no constructor newstack().
Instead there his one linkable variable empty_arr_stack,
whose clone() can be used to make new empty array stacks.
See main2.c for usage. */
const stack empty_arr_stack /* made const as by MAA */
= {/* initialize */
&empty_arr
,array_isempty
,array_push
,array_pop
,array_clone
,array_delete_stack
}; /* end stack empty_arr_stack */
stackptr new_arr_stack(void)
/* instead of calling the clone function in empty_arr_stack,
make a callable function that does that.
Then empty_arr_stack need not be declared in calling program */
{extern const stack empty_arr_stack;
return (*empty_arr_stack.clone)(&empty_arr_stack);
}/* end new_arr_stack */