Hi remember me? I posted here a few months ago with a problem using a stack. Well now I’m using the same stack code again but trying to make the stack with pointers (yay I’m learning pointers!). Anyway I have been playing with this code for a long time and I am nearly insane because it is not working and I cant find out where the problem is. I know it is probably a stupid and small mistake of mine but I cant find it.
When this program is run if the input is 123 the output should be 321
I’m sure that this code is very easy to understand for anyone who knows C better than me so please tell me what is wrong with my code before I go crazy.
Thankyou.
Code:#include <stdio.h> #include <stdlib.h> #define STACK_SIZE 50 #define TRUE 1 #define FALSE 0 typedef int Bool; void make_empty(void); Bool is_empty(void); Bool is_full(void); void push(int i); int pop(void); void stack_overflow(void); void stack_underflow(void); int contents[STACK_SIZE]; int *top_ptr = &contents[0]; int main() { int temp = 0; make_empty(); printf("Enter some digits: "); while ((temp = getchar()) != '\n') { push(temp); } printf("Contents of stack (should be reversed): "); while (!is_empty()) { printf("%d", pop()); } printf("\n"); return 0; } void make_empty(void) { top_ptr = &contents[0]; } Bool is_empty(void) { return top_ptr == &contents[0]; } Bool is_full(void) { return top_ptr == &contents[STACK_SIZE]; } void push(int i) { if (is_full()) stack_overflow(); else *top_ptr++ = i; } int pop(void) { if (!is_empty()) return *--top_ptr; else stack_underflow(); return 0; } void stack_overflow(void) { printf("Stack Overflow!\n"); exit(EXIT_FAILURE); } void stack_underflow(void) { printf("Stack Underflow!\n"); exit(EXIT_FAILURE); }