Skip to content

Instantly share code, notes, and snippets.

@oriapp
Last active August 19, 2022 14:21
Show Gist options
  • Save oriapp/9555a20339f6245b485d602db33a9208 to your computer and use it in GitHub Desktop.
Save oriapp/9555a20339f6245b485d602db33a9208 to your computer and use it in GitHub Desktop.
Generic type stack impl
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum
{
STACK_INT,
STACK_CHAR,
STACK_UINT64
} DataType;
typedef struct Stack
{
DataType type;
size_t size;
void *data;
void *top;
int load;
} Stack;
Stack stackCreate(size_t size, DataType type)
{
size_t sizedMalloc = 0;
switch (type)
{
case STACK_CHAR:
sizedMalloc = size * sizeof(char); // 1 byte
break;
case STACK_INT:
sizedMalloc = size * sizeof(int); // 4 byte
break;
case STACK_UINT64:
sizedMalloc = size * sizeof(unsigned long long); // 8 byte
break;
}
Stack s = {
.type = type,
.size = size,
.data = malloc(sizedMalloc),
.top = NULL,
.load = 0,
};
return s;
}
void stackFree(Stack *s)
{
// Free allocated meme
free(s->data);
s->data = NULL;
}
int stackFull(Stack *stack)
{
return stack->load <= stack->size;
}
void abortStack(Stack *stack)
{
printf("here\n");
stackFree(stack);
fprintf(stderr, "Stack is full\n");
}
// Stack push block [START]
void stackPushInt(Stack *stack, int element)
{
if (!stackFull(stack))
return abortStack(stack);
((int *)stack->data)[stack->load] = element;
stack->top = ((int *)stack->data) + stack->load;
stack->load++;
}
void stackPushChar(Stack *stack, char element)
{
if (!stackFull(stack))
return abortStack(stack);
((char *)stack->data)[stack->load] = element;
stack->top = ((char *)stack->data) + stack->load;
stack->load++;
}
void stackPushUint64(Stack *stack, unsigned long long element)
{
if (!stackFull(stack))
return abortStack(stack);
((unsigned long long *)stack->data)[stack->load] = element;
stack->top = ((unsigned long long *)stack->data) + stack->load;
stack->load++;
}
#define stackPush(x, y) _Generic(y, int \
: stackPushInt, char \
: stackPushChar, unsigned long long \
: stackPushUint64)(x, y)
// Stack push block [END]
int main(int arvc, char *argv[])
{
Stack stack = stackCreate(10, STACK_INT);
int counter = 1;
for (size_t i = 0; i < 10; i++)
{
stackPush(&stack, counter++);
}
printf("top is: %d\n", *((int *)stack.top));
stackFree(&stack);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment