Hello everyone,
I'm trying to build a program to evaluate fully parenthesized expressions. We have to use stacks, and we have to use pointers to point to the stacks. I'm having a lot of trouble with the pointers, and I'm debugging it with gdb and a lot of values seem out of whack and some values change while others seem not to, like the *top. here's what I have:
Code:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_SIZE 20
void push(int* stack, int* top, int element);
int pop(int* stack, int* top);
bool is_empty(int* top);
bool is_full(int* top);
void stack_overflow(void);
void stack_underflow(void);
int evaluate(int i, int j, int k);
int main(void){
int top1=0,top2=0;
int *top_operators=&top1;
int *top_operands=&top2;
int stack_operands[STACK_SIZE];
int stack_operators[STACK_SIZE];
int *operands = &stack_operands[0];
int *operators = &stack_operators[0];
char next;
int temp, temp1, result;
scanf("%c", &next);
while(next!='='){
if(next=='+' || next=='-' || next=='*' || next=='/')
push(operators,top_operators,next);
else if(isdigit(next)){
temp=next-'0';
push(operands,top_operands,next);
}
else if(next==')'){
temp=pop(operands,top_operands);
temp1=pop(operands,top_operands);
result=(temp,temp1,pop(operators,top_operators));
push(operands,top_operands,result);
}
else if(next!='('){
printf("Invalid input.");
exit(EXIT_FAILURE);
}
scanf("%c",&next);
}
result=pop(operands,top_operands);
if(!is_empty(top_operands) || !is_empty(top_operators)){
printf("Invalid input.");
exit(EXIT_FAILURE);
}
else{
printf("%d\n",result);
return(0);
}
}
void push(int* stack, int* top, int element){
if(is_full(top))
stack_overflow();
else
*(stack+(*top++))=element;
}
int pop(int* stack, int* top){
if(is_empty(top))
stack_underflow();
else
return *(stack+(--*top));
}
bool is_empty(int* top){
return *top==0;
}
bool is_full(int* top){
return *top == STACK_SIZE;
}
void stack_overflow(void){
printf("Error. Stack overflow.\n");
exit(EXIT_FAILURE);
}
void stack_underflow(void){
printf("Error. Stack underflow.\n");
exit(EXIT_FAILURE);
}
int evaluate(int i, int j, int k){
int result;
if(k=='+')
result=(i+j);
else if(k=='-')
result=(i-j);
else if(k=='*')
result=(i*j);
else
result=(i/j);
return result;
}