#include <stdio.h>
#include <stdlib.h>
struct Stack {
int value;
int is_empty;
struct Stack *next;
};
int pop(struct Stack **stack) {
if ((*stack)->is_empty == 1) {
printf("Stack is empty!\n");
abort(); // not sure what this does
} else {
int value = (*stack)->value;
// outer pointer (static) points to new stack now
*stack = (*stack)->next;
return value;
}
}
void push(struct Stack **stack, int value) {
// malloc is used so this memory can be accessed outside of scope
struct Stack *head = malloc(sizeof(struct Stack*));
if (head != NULL) {
head->value = value;
// head's next is pointer to stack
head->next = *stack;
head->is_empty = 0;
// stack now holds pointer to head
*stack = head;
} else {
printf("push memory no alloc");
}
}
struct Stack *empty() {
struct Stack *head = malloc(sizeof(struct Stack *));
if (head != NULL) {
head->value = 0;
head->is_empty = 1;
head->next = NULL;
return head;
} else {
return NULL;
}
}
int main() {
struct Stack *init = empty();
struct Stack **stack = &init;
push(stack, 3);
push(stack, 2);
push(stack, 1);
int one = pop(stack);
printf("one: %d\n", one);
int two = pop(stack);
printf("two: %d\n", two);
int three = pop(stack);
printf("three: %d\n", three);
//int hmm = pop(stack);
}
I'm not sure pointers to pointers is the best way to do this. I also feel like I'm writing code in a Java-y way, and would like to know how to improve my C style.
Also, are there any edge cases I am missing?