cds

C data structures
Index Commits Files Refs LICENSE
stack.c (1016B)
   1 /* Stack implementation using a vector to store the elements */
   2 
   3 #include "stack.h"
   4 
   5 #include <stdio.h>
   6 #include <string.h>
   7 
   8 void stack_new(Stack **S, size_t mem_width) {
   9     (*S) = malloc(sizeof(Stack));
  10     (*S)->vector = malloc(sizeof(Stack *) * STACK_INITIAL_ALLOC);
  11     (*S)->mem_width = mem_width;
  12     (*S)->mem_alloc = STACK_INITIAL_ALLOC;
  13     (*S)->len = 0;
  14 }
  15 
  16 /* generates a copy of the element an push it into stack
  17  * does not check if elem is valid type */
  18 void stack_push(Stack *S, const void *elem) {
  19     if(S->mem_alloc == S->len)
  20         S->vector = realloc(S->vector, 
  21                 (S->mem_alloc *= STACK_GROWTH_FACTOR) * sizeof(Stack *));
  22 
  23     S->vector[S->len] = malloc(S->mem_width);
  24     memcpy(S->vector[S->len++], elem, S->mem_width);
  25 }
  26 
  27 void stack_peek(const Stack *S, void *data) {
  28     data = S->len ? S->vector[S->len - 1] : NULL;
  29 }
  30 
  31 void stack_pop(Stack *S, void *data) {
  32     if(S->len) {
  33         memcpy(data, S->vector[--S->len], S->mem_width);
  34         free(S->vector[S->len]);
  35     }
  36 }
  37 
  38 void stack_destroy(Stack *S) {
  39     free(S->vector);
  40     free(S);
  41 }
  42