It is already clear at first glance that something is overwritten here:
char exp[20];
char *e;
int n1, n2, n3, num, len;
len = strlen(exp);
printf("Enter the expression :: ");
scanf("%s", exp);
e = exp;
for (*e = len - 1; *e >= 0; *e--) { ...
You declare a pointer e that points first to nothing, then to the entered data.
Then the data is overwritten with the length.
In the further course then naturally still further goes wrong. Pop is called several times without push having been called before ...
The variables n1 and n2 have nonsensical values afterwards and although the calculation of n3 has not taken place the undefined value of n3 is then also pushed.
Almost every line of the program seems to go sief somehow ...
The two global variables should also be avoided, better encapsulate everything in a class or keep local.
int stack[20], top = -1;
//Edit:
Further references to a similar program of yours have already been given here:
A code for prefix expression evaluation in C using stacks not running[
^]
The current program is not an improvement over the source code you presented there. The error even occurs at the same place.
int len;
char prefix[20];
int res,i;
gets(prefix);
len=strlen(prefix);
for(i=len-1;prefix[i]>=0;i--) { ...
So I repeat here the urgent suggestion to start the loop at 0.
//edit2:
Quote:
i want to traverse the expression from right to left
If that is the goal, as already mentioned, quite a few changes might be necessary.
But then this place cannot work, because the second operand has not been processed at that time.
n1 = pop();
n2 = pop();
Here's an example based on your code how it might work:
char exp[20];
char op, *e;
int num, len;
printf("Enter the expression :: ");
scanf("%s", exp);
len = strlen(exp);
for (e = &exp[len-1]; e >= exp; e--)
{
if (isdigit(*e)) {
num = *e - 48;
push(num);
}
else {
op = *e;
}
}
int n1, n2, n3;
It might be more obvious to push the operand instead of the numbers.
And before I get hit, here's an urgent hint: NEVER use the scanf() function with strings! Better use fgets() or another function that can handle constrained arrays.