njvm/stack.c
2023-12-09 21:55:12 +01:00

50 lines
1.1 KiB
C
Executable File

//
// Created by Nils on 29.10.2023.
//
#ifndef STACK
#define STACK
#include <stdio.h>
#include <stdlib.h>
struct stack {
int* size;
int* current;
unsigned int *stack;
};
void printStack(struct stack stack, int fp) {
printf("Stack\nSize:\t\t%i\nCurrent:\t%i\n", *stack.size, *stack.current);
for (int i = 0; i < *stack.current; ++i) {
if(fp == i) printf("|FP|\n");
printf("|%i|\n", stack.stack[i]);
}
}
void push(struct stack s, unsigned int value) {
if (*s.current >= *s.size) {
printf("Stack Overflow\n");
exit(EXIT_FAILURE);
}
s.stack[*s.current] = value;
*s.current=*s.current + 1;
}
unsigned int pop(struct stack s) {
if (*s.current == 0) {
printf("Stack Underflow\n");
exit(EXIT_FAILURE);
}
*s.current = *s.current -1;
return s.stack[*s.current];
}
unsigned int peek(struct stack s, int steps) {
if (*s.current - steps < 0) {
printf("Stack Underflow\n");
exit(EXIT_FAILURE);
}
return s.stack[*s.current - steps];
}
#endif