Listing 10 Implements multiple stacks of integers via arrays

/* stack2.c */

#include "stack2.h"

#define MAX_STACKS  16
#define STACK_SIZE 100

static struct stack
{
   int data[STACK_SIZE];
   int ptr;
   int active;
} stacks[MAX_STACKS];

int stack_open(void)
{
   int i;

   /* Activate an inactive stack */
   for (i = 0; i < MAX_STACKS; ++i)
      if (!stacks[i].active)
      {
         stacks[i].ptr = 0;
         stacks[i].active = 1;
         return i;
      }

   return STACK_ERROR;
}

int stack_push(int id, int x)
{
   if (id >= 0 && id < MAX STACKS &&
      stacks[id].active)
   {
      int ptr = stacks[id].ptr;

      if (ptr == STACK_SIZE)
         return STACK_ERROR;
      else
      {
         stacks[id].data[ptr] = x;
         ++stacks[id].ptr;
         return x;
      }
   }
   else
      return STACK_ERROR;
}

int stack_pop(int id)
{
   if (id >= 0 && id < MAX_STACKS &&
      stacks[id].active)
   {
      int ptr = stacks[id].ptr;

      if (ptr == 0)
         return STACK_ERROR;
      else
      {
         ptr = --stacks[id].ptr;
         return stacks[id].data[ptr];
      }
   }
   else
      return STACK_ERROR;
}

void stack_close(int id)
{
   if (id >= 0 && id < MAX_STACKS)
      stacks[id].active = 0;
}

/* End of File */