I have been asked to calculate a postfix expression , which means that for every consequtive 2 numbers there is an arithmetical operation in between , for example fot the given string “123*+” the result will be 7 –> 1+(2*3)
I tried to write the code in C but for some reason i get that the result is 0
can someone tell me why? or if my direction is wrong?
And how can i return to the user that there was an error with the given string such as uknown char or empty string if the function needs to return an int. I can’t return NULL right.?
thank you
#include <stdio.h>
#define ERROR -2147483648
int Postfix(char *str) {
if(!str)
return ERROR;
int str_length;
for ( str_length = 0;str[str_length]!=''; str_length++); // calculating the exact number of chars in the string
int mid=str_length/2;// the length of the string will always be odd because its not possible that the number of digits equals to the number of arithmetics puncuation sice for every artihmetic
//puncutation there are 2 digits.
int *current, *prev, result=0;
char *arithmetic;
arithmetic=str+mid+2;// address of the first arithemetic sign in the array
prev=str+mid;// address of the second last digit in the array
current=str+mid+1; // address of the last digit in the array
for (int i = 0; i < mid; i++) { // the loop will run the exact number of arithmetic operations
prev=str+mid-i;
arithmetic=str+mid+i;
switch(*arithmetic) {
case '+': {
result+=(*current)+(*prev);
break;
}
case '-': {
result+=(*current)-(*prev);
break;
}
case '*': {
result+=(*current)*(*prev);
break;
}
case '/': { // need to handle the case with division by 0?
result+=(*current)/(*prev);
break;
}
default: { // need to handle the case where an arithmetic which is not (+,-,*,/) was inserted?
result+=0;
break;
}
}
*current=result;
}
return result;
}
int main() {
char c[]="231*+";
int result=Postfix(&c);
printf("%d",result);
if(result!=ERROR)
printf("The result is: %d",result);
else
printf("An error occured.");
return 0;
}