C 用指针计算后缀表达式?
我必须计算C中的后缀表达式。 这不会是一个太大的挑战,但我不需要使用下标符号,而只需要使用指针进行交互。 我对指针非常陌生,需要一些帮助来转换我的代码,使用下标符号将其转换为只与指针交互的代码。 任何帮助都将不胜感激C 用指针计算后缀表达式?,c,pointers,stack,postfix-notation,C,Pointers,Stack,Postfix Notation,我必须计算C中的后缀表达式。 这不会是一个太大的挑战,但我不需要使用下标符号,而只需要使用指针进行交互。 我对指针非常陌生,需要一些帮助来转换我的代码,使用下标符号将其转换为只与指针交互的代码。 任何帮助都将不胜感激 //libraries #include <stdio.h> //for input and output #include <ctype.h> //for isdigit function #include <math
//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--]);
}
//库
#包括//用于输入和输出
#isdigit函数的include//
#包括//用于pow功能
#定义大小50//数组的大小
//全局变量
int堆栈[大小];
int top=-1;
//原型
空推(浮动);
int-pop();
//进入主功能
内部主(空)
{
charexp[50],c;
int i=0;
浮动x,y;
//提示用户输入公式
printf(“请用后缀符号输入表达式:\n”);
//在字符数组exp中存储公式
扫描频率(“%s”,exp);
//开始while循环以读取数组
而((c=exp[i++])!='\0')
{
//如果它是一个操作数,则按下
if(isdigit(c))
推(c-'0');
//如果是运算符,则将两个操作数推到顶部并求值
其他的
{
x=pop();
y=pop();
//确定已完成的操作
开关(c)
{
格“+”:
推(x+y);
打破
案例'-':
推(x-y);
打破
案例“*”:
推力(x*y);
打破
案例“/”:
推力(x/y);
打破
案例‘^’:
推力(功率(x,y));
}
}
}
printf(“\n\n计算表达式将等于:%d\n”,堆栈[top]);
}
空推(浮动z)
{
堆栈[++顶部]=z;
}
int-pop()
{
返回(堆栈[顶部--]);
}
通常,只要记住以下定义就足够了:
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)
有了这个想法,您可以使用指向数组的指针访问数组,并通过将索引
替换为指针解引用