Skip to content

Instantly share code, notes, and snippets.

@zaccone
Created September 5, 2016 18:11
Show Gist options
  • Save zaccone/9c98fa5bc78d2d9b0a0032bcbc5d5a69 to your computer and use it in GitHub Desktop.
Save zaccone/9c98fa5bc78d2d9b0a0032bcbc5d5a69 to your computer and use it in GitHub Desktop.
Generic stack in ANSI C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct stack {
size_t capacity;
size_t size;
size_t pos;
size_t us;
void *container;
} stack;
stack *newStack(size_t capacity, size_t unitSize)
{
stack *s = (stack *) malloc(sizeof(stack));
s->capacity = capacity;
s->pos = 0;
s->us = unitSize;
s->container = malloc(unitSize * capacity);
return s;
}
int push(stack * s, void *v)
{
if (!s)
return -1;
if (s->pos == s->capacity) {
return -1;
}
memcpy(s->container + s->us * s->pos, v, s->us);
s->pos++;
return 0;
}
void pop(stack * s)
{
if (!s || !s->pos)
return;
s->pos--;
}
void *top(stack * s)
{
if (!s || !s->pos)
return NULL;
return (char *)(s->container + (s->pos - 1) * s->us);
}
int main()
{
stack *s = newStack(10, sizeof(int));
for (int i = 0; i < 10; i++) {
int ii = i * 10000;
int res = push(s, &ii);
printf("Pushed %d (res=%d)\n", ii, res);
}
int x = 10;
while (x--) {
printf("%d\n", *(int *)top(s));
pop(s);
}
stack *s2 = newStack(10, sizeof(char **));
const char *marek = "marek";
const char *ania = "anna";
push(s2, (void *)&marek);
push(s2, (void *)&ania);
char *t1 = *(char **)top(s2);
printf("Got: %s\n", *(char **)top(s2));
pop(s2);
printf("Got: %s\n", *(char **)top(s2));
pop(s2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment