I have to evaluate a postfix expression in C. This wouldn't be too must of a challenge but instead of using subscript notation I have to interact only using a pointer. I'm extremely new to pointers and need some help converting the code I have, using subscript notation into one that only interacts with a pointer. Any help would be greatly appreciated.
//libraries
#include <stdio.h> //for input and output
#include <ctype.h> //for isdigit function
#include <math.h> //for pow function
#define size 50 //size of the array
//global variables
int stack[size];
int top=-1;
//Prototypes
void push(float);
int pop();
//Enter main function
int main(void)
{
char exp[50], c;
int i=0;
float x, y;
//Prompt user to enter equation
printf("Please enter your expression in postfix notation:\n");
//store equation in character array exp
scanf("%s", exp);
//Begin while loop to read through the array
while( (c = exp[i++]) != '\0')
{
//If it is a operand, push
if(isdigit(c))
push(c-'0');
//If it is an operator push two operands on top and evaluate
else
{
x = pop();
y = pop();
//Determining operation done
switch(c)
{
case '+':
push(x + y);
break;
case '-':
push(x - y);
break;
case '*':
push(x * y);
break;
case '/':
push(x / y);
break;
case '^':
push(pow(x,y));
}
}
}
printf("\n\n Evaluated expression will equal: %d\n",stack[top]);
}
void push(float z)
{
stack[++top] = z;
}
int pop()
{
return(stack[top--]);
}
Usually, it's enough to remember that, with a definition like:
int xyzzy[10];
these two are equivalent:
xyzzy[4]
*(xyzzy + 4)
So that's how you can get access to array elements without an actual subscript.
In other words, rather than:
stack[++top] = z;
return(stack[top--]);
you can instead use:
*(++top + stack) = z;
return *(top-- + stack);