74 lines
1.3 KiB
C
74 lines
1.3 KiB
C
#include<stdio.h>
|
|
#include<stdlib.h>
|
|
|
|
typedef struct {
|
|
int* st;
|
|
int cnt;
|
|
int size;
|
|
} STACK;
|
|
|
|
STACK* init_stack(int size) {
|
|
if (size <= 0) {
|
|
return NULL;
|
|
}
|
|
STACK *buf;
|
|
buf = malloc(sizeof(STACK));
|
|
if (buf == NULL) {
|
|
fprintf(stderr, "Error allocating structure\n");
|
|
return NULL;
|
|
}
|
|
buf -> st = malloc(sizeof(int)*size);
|
|
if (buf -> st == NULL) {
|
|
fprintf(stderr, "Error allocating array\n");
|
|
free(buf);
|
|
return NULL;
|
|
}
|
|
buf -> cnt = 0;
|
|
buf -> size = size;
|
|
return buf;
|
|
}
|
|
|
|
void destroy_stack(STACK* s) {
|
|
free(s -> st);
|
|
free(s);
|
|
}
|
|
|
|
void push(STACK* st, int val) {
|
|
if ((st -> cnt) < (st -> size)) {
|
|
st -> st[st -> cnt] = val;
|
|
(st -> cnt)++;
|
|
} else {
|
|
fprintf(stderr, "Stack is full! Stack size is %d, value to add is %d\n", st -> size, val);
|
|
}
|
|
}
|
|
|
|
int pop(STACK* st) {
|
|
if ((st -> cnt) > 0) {
|
|
(st -> cnt)--;
|
|
return st -> st[st -> cnt];
|
|
|
|
} else {
|
|
fprintf(stderr, "Attempted to pop an empty stack\n");
|
|
return NULL;
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
printf("What's the meaning of my life?\n");
|
|
STACK* huh = init_stack(5);
|
|
push(huh, 3);
|
|
push(huh, 2);
|
|
push(huh, 4);
|
|
printf("%d", pop(huh));
|
|
printf("%d\n", pop(huh));
|
|
printf("Nice. Let's try to overflow this stack now,\n");
|
|
push(huh, 3);
|
|
push(huh, 3);
|
|
push(huh, 3);
|
|
push(huh, 3);
|
|
push(huh, 3);
|
|
printf("thx bye\n");
|
|
return 0;
|
|
}
|
|
|