2 * An implementation of a char stack in heap memory.
3 * Copyright (C) 2014 Michael Goehler
5 * This file is part of mdp.
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include <stdio.h> // fprintf
23 #include <stdlib.h> // malloc, realloc
27 cstack_t *cstack_init() {
28 cstack_t *stack = NULL;
29 if((stack = malloc(sizeof(cstack_t))) != NULL) {
30 stack->content = NULL;
31 stack->alloc = stack->size = 0;
33 stack->push = cstack_push;
34 stack->pop = cstack_pop;
35 stack->top = cstack_top;
36 stack->empty = cstack_empty;
37 stack->delete = cstack_delete;
39 fprintf(stderr, "%s\n", "cstack_init() failed to allocate memory.");
45 void cstack_push(cstack_t *self, char c) {
46 if(self->size + sizeof(c) > self->alloc) {
47 self->alloc += (sizeof(char));
48 if((self->content = realloc(self->content, self->alloc)) == NULL) {
49 fprintf(stderr, "%s\n", "cstack_push() failed to reallocate memory.");
53 self->content[++self->head] = c;
54 self->size += (sizeof(char));
57 char cstack_pop(cstack_t *self) {
58 self->size -= (sizeof(char));
59 return self->content[self->head--];
62 int cstack_top(cstack_t *self, char c) {
63 if(self->head >= 0 && self->content[self->head] == c)
68 int cstack_empty(cstack_t *self) {
69 return self->head == -1;
72 void cstack_delete(cstack_t *self) {