Skip to content

Instantly share code, notes, and snippets.

@panta
Created December 9, 2021 17:48
Show Gist options
  • Save panta/afddc96fe2df0340e107454cfe703052 to your computer and use it in GitHub Desktop.
Save panta/afddc96fe2df0340e107454cfe703052 to your computer and use it in GitHub Desktop.
UNIPD FdI 2021-2022 - Esempio di stack in C (con struct e variabili locali)
#include <stdio.h>
#include <stdint.h>
#define STACK_SIZE 1000
struct stack {
int elements[STACK_SIZE];
int sp;
};
void stack_init(struct stack *stack) {
stack->sp = 0;
}
void stack_push(struct stack *stack, int val) {
stack->elements[stack->sp] = val;
stack->sp++;
}
int stack_pop(struct stack *stack) {
int r = stack->elements[--stack->sp];
return r;
}
void stack_print(struct stack *stack) {
for (int i = stack->sp - 1; i >= 0; i--) {
printf("stack[%d]: %d\n", i, stack->elements[i]);
}
}
int main() {
struct stack st;
stack_init(&st);
stack_push(&st, 88);
stack_push(&st, 15);
stack_push(&st, 42);
stack_push(&st, 111);
stack_push(&st, 333);
stack_print(&st);
int r = stack_pop(&st);
printf("popped %d\n", r);
r = stack_pop(&st);
printf("popped %d\n", r);
printf("\n");
stack_print(&st);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment