Skip to content

Instantly share code, notes, and snippets.

@storca
Last active November 13, 2021 10:58
Show Gist options
  • Save storca/afd806b0c288dddcb52de899c510e145 to your computer and use it in GitHub Desktop.
Save storca/afd806b0c288dddcb52de899c510e145 to your computer and use it in GitHub Desktop.
Stack data structure in C
/**
* @file stack.c
* @author storca (storca@mail.com)
* @brief Implementation of a stack in C with a fixed size
*/
#define STACK_SIZE 64
#include <stdio.h> //printf
#include <string.h> //memcpy
#include <stdlib.h> //malloc, free
//Macro static cast
#define F(X) (char*)&X
typedef struct {
char *data;
u_int8_t index;
u_int8_t type_size;
} Stack;
void init_stack(Stack **s, size_t type_size)
{
//Allocation pour le type Stack en premier
*s = malloc(sizeof(Stack));
(*s)->type_size = type_size;
//Allocation de l'espace pour les données en deuxième
(*s)->data = (char*)calloc(STACK_SIZE, type_size);
(*s)->index = 0;
}
void push_stack(Stack *s, char* data)
{
memcpy(&(s->data[ s->index * s->type_size ]), data, s->type_size);
if(s->index < STACK_SIZE)
{
s->index++;
}
}
char* top_stack(Stack *s)
{
return &s->data[s->index * s->type_size];
}
char* get_stack(Stack *s)
{
if(s->index > 0)
{
s->index--;
return &s->data[s->index * s->type_size];
}
else
{
return &s->data[0];
}
}
void delete_stack(Stack *s)
{
//Deallocation des données
free(s->data);
//Deallocation de la structure
free(s);
}
void dump_stack(Stack *s)
{
for (size_t i = 0; i < STACK_SIZE*s->type_size; i++)
{
printf(" %hhx", s->data[i]);
}
for (size_t i = 0; i < STACK_SIZE; i++)
{
printf("%i ", *(int*)&(s->data[4*i]));
}
}
int main()
{
int ye = 2346;
Stack *s;
init_stack(&s, sizeof(int));
push_stack(s, F(ye));
ye = 65412;
push_stack(s, F(ye));
printf("Get : %i\n", *(int*)get_stack(s));
printf("Top : %i\n", *(int*)top_stack(s));
printf("Get : %i\n", *(int*)get_stack(s));
delete_stack(s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment