用指针评估后缀表达式?

时间:2014-04-02 07:27:58

标签: c pointers stack postfix-notation

我必须在C中评估一个后缀表达式。 这不是一个挑战,但不是使用下标符号,我必须只使用指针进行交互。 我是指针的新手,需要一些帮助来转换我的代码,使用下标符号到只与指针交互的符号。 任何帮助将不胜感激。

//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--]);
}

2 个答案:

答案 0 :(得分:1)

通常情况下,用以下定义来记住它就足够了:

int xyzzy[10];

这两个是等价的:

xyzzy[4]
*(xyzzy + 4)

这就是如何在没有实际下标的情况下访问数组元素。

换句话说,而不是:

stack[++top] = z;
return(stack[top--]);

你可以改用:

*(++top + stack) = z;
return *(top-- + stack);

答案 1 :(得分:-1)

如果您知道如何使用指针访问数组,则很容易将此代码转换为仅使用指针的代码。

char *str;
str=exp;

然后你可以访问

exp[i]

使用指针

*(str+i)

这两个陈述是平等的 为了更清楚,在char数组exp []中,exp被称为基指针,因此它就像一个指针和

exp[i] is same as *(exp+i)

有了这个想法,您可以使用指向数组的指针访问数组,并通过用indexing

替换pointer dereferencing来更改代码