繁体   English   中英

用指针评估后缀表达式?

[英]Evaluating postfix expression with a pointer?

我必须在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--]);
}

通常,只要记住这样的定义就足够了:

int xyzzy[10];

这两个是等效的:

xyzzy[4]
*(xyzzy + 4)

这样便可以在没有实际下标的情况下访问数组元素。

换句话说,而不是:

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

您可以改用:

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

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

char *str;
str=exp;

然后您可以访问

exp[i]

使用指针作为

*(str+i)

这两个陈述是相等的。
更清楚地说,在char数组exp []中, exp被称为基本指针,因此它就像一个指针,并且

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

有了这个主意,您可以使用指向数组的指针访问数组,并通过使用此pointer dereferencing替换indexing来更改代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM