Program compiles successfully, as I am trying to implement the timeless postfix algorithm using a stack.
It seems to, no matter what input I'm using, loop through 256 times until it encounters an overflow, as the stack is full.
Where am I pushing on the elements 256 times?
Code:
#include <stdio.h>
#define STACKSIZE 256
#define TRUE 1
#define FALSE 0
/* stack type definition */
typedef struct {
int top;
int items[STACKSIZE];
} stack_type;
/* function prototypes */
void push(stack_type*, float); /* void, as nothing is returned */
float pop(stack_type*);
int main(void)
{
char buffer[256];
char input[STACKSIZE];
stack_type stk;
int i=0;
stk.top = -1; /* Initialize the stack to empty */
printf("This program will evaluate postfix expressions using a\n");
printf("good implementation of stacks.\n");
printf("You may enter up to a 50-char expression.\n");
printf("Please enter a postfix/reverse-polish expression for me.\n");
fgets(input, sizeof(input), stdin);
while (1) {
for (i=0; i<STACKSIZE; i++) {
switch(input[i]) {
case '+':
push(&stk, (input[i] - 48));
push((&stk), pop(&stk) + pop(&stk));
break;
case '-':
push(&stk, input[i] - 48);
push((&stk), pop(&stk) - pop(&stk));
break;
case '*':
push(&stk, input[i] - 48);
push((&stk), pop(&stk) * pop(&stk));
break;
case '/':
push(&stk, input[i] - 48);
push((&stk), pop(&stk) / pop(&stk));
break;
case '1':
push(&stk, input[i] - 48);
break;
case '2':
push(&stk, input[i] - 48);
break;
case '3':
push(&stk, input[i] - 48);
break;
case '4':
push(&stk, input[i] - 48);
break;
case '5':
push(&stk, input[i] - 48);
break;
case '6':
push(&stk, input[i] - 48);
break;
case '7':
push(&stk, input[i] - 48);
break;
case '8':
push(&stk, input[i] - 48);
break;
case '9':
push(&stk, input[i] - 48);
break;
case '0':
push(&stk, input[i] - 48);
break;
default:
printf("Invalid Input\n"); }
}
}
return 0;
}
/* IS Empty */
float is_empty(stack_type* stk)
{
if ( (*stk).top == -1 )
return TRUE;
else
return FALSE;
}
/* Push */
void push(stack_type* stk, float element)
{
if ( stk == NULL )
{ printf("Warning! Stack pointer is set to NULL.\n");
exit(1); /* exit the program */
}
/* check stack is not full */
if ( (*stk).top == (STACKSIZE - 1) )
{ printf("Stack Overflow!\n");
exit(1);
}
/* increment stack top */
(*stk).top++;
/* add the new element to the top */
(*stk).items[(*stk).top] = element;
return;
}
/* Pop */
float pop(stack_type* stk)
{ float value=0;
/* Check stack exists */
if ( stk == NULL )
{ printf("Warning! Stack pointer is set to NULL. Is it really there?\n");
exit(1);
}
/* check that the stack is not empty */
if (is_empty(stk))
{ printf("Stack underflow!\n");
exit(1);
}
/* get top item */
value = (*stk).items[(*stk).top];
/* decrement top */
(*stk).top--;
/* return popped item to calling f(x); */
return value;
}