This is my attempt to code a postfix calculator using a stack. I have two functions pop and push and the variable l indicate the last element. When executed with the terminal, it should be like this:
./postfix 3 2 +
5
instead I get the error : floating point exception.
I cannot find where the error comes from.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define STACK_SIZE_MAX 1024
int tab[1024] = {};
int l = 0; // last element to be used
void push(int x)
{
tab[l] = x;
l++;
}
int pop()
{
int x = tab[l-1];
l--;
return x;
}
int main(int argc, char *argv[])
{
// reading arguments one by one
int i =1;
for(i; i < argc; i++){
switch(*(argv[i]))
{
case '+':
{
int x = pop();
int y = pop();
int s = x + y;
push(s);
}
case '-':
{
int x = pop();
int y = pop();
int s = x - y;
push(s);
}
case '*':
{
int x = pop();
int y = pop();
int s = x * y;
push(s);
}
case '/':
{
int x = pop();
int y = pop();
int s = x / y;
push(s);
}
default:
// if it is a number we push it to the stack
push(atoi(argv[i]));
break;
}
}
// display the result
printf("the result is : %d ",tab[0]);
}