【发布时间】:2019-03-15 23:18:23
【问题描述】:
我编写这个伪代码是因为我想尝试构建一个我在更大程序中使用的基本计算器。如下:
对于每个令牌t:
如果t 是运算符或左括号,则将其压入操作数堆栈。
否则,如果t 是右括号:
反复弹出操作数堆栈,直到碰到左括号。对于找到的每个运算符:
- 两次弹出值栈以获取操作数。
- 对这些操作数执行操作。
- 将操作结果推送到值栈中。
否则t 表示一个数字。
将t 转换为整数,并将其压入值堆栈。
当你没有令牌时,重复弹出操作数堆栈直到它为空,像以前一样执行每个操作。此时值栈上应该有一个数字,这就是答案。
然而,当我编写代码时,它给了我一个分段错误。我知道这与内存有关,但我不确定如何修复它或者是否需要为此功能分配内存。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
不确定这是否写得正确或是否会引发错误?
int operandApplication(int a, int b, char op){
if (op == '+'){
return a + b;
}
else {
return a * b;
}
}
int popValStack(int valstack[], int *top){
int valdata = valstack[*top];
*top = *top - 1;
return valdata;
}
void pushValStack(int valstack[], int *top, int value){
*top = *top + 1;
valstack[*top] = value;
}
char *popOpStack (char *charstack[], int *top){
char *chardata = charstack[*top];
*top = *top -1;
return chardata;
}
void pushOpStack (char *charstack[], int *top, char *value){
*top = *top + 1;
charstack[*top] = value;
}
是否需要使用 malloc 在以下主函数中分配内存?
int main(int argc, char *argv[]){
int i;
int valueStack[50];
int valcounter = 0;
int opcounter = 0;
int l;
int m;
char *opStack[50];
char *op;
for(i = 1; i < argc; i++){
我在这里使用了字符串比较,因为它看起来更容易,但不确定它是否有用。
char *t = argv[i];
int s1 = strcmp(t, "[");
int s2 = strcmp(t, "+");
int s3 = strcmp(t, "x");
int s4 = strcmp(t, "]");
if(s1 == 0 | s2 ==0 | s3 == 0){
pushOpStack(opStack, &opcounter, argv[i]);
}
else if(s4 == 0){
char *S = popOpStack(opStack, &opcounter);
while (*S!= '[') {
int a = popValStack(valueStack, &valcounter);
int b = popValStack(valueStack, &valcounter);
pushValStack (valueStack, &valcounter, operandApplication(a, b, *S));
}
}
else {
int x = atoi(t);
pushValStack(valueStack, &valcounter, x);
}
}
while (opcounter > 0){
op = popOpStack(opStack, &opcounter);
l = popValStack(valueStack, &valcounter);
m = popValStack(valueStack, &valcounter);
pushValStack (valueStack, &valcounter,
operandApplication(l, m, *op));
}
printf ("%d\n", valueStack[valcounter]);
}
【问题讨论】:
-
请选择一种语言。我们还需要知道您正在使用的输入。如果您希望其他人可能编译您的代码,最好硬编码而不是使用命令行参数。
-
你能给我们一个导致段错误的输入的例子吗?