我在该程序中将行中缀转换为后缀时在行210和135上收到未初始化的局部变量错误。你能告诉我我做错了吗?
/*
1)
infix: A*B+C
postfix: AB*C+
2)
infix: A+B*C
postfix: ABC*+
3)
infix: A*B+C*D
postfix: AB*CD*+
4)
infix: A*B^C+D
postfix: ABC^*D+
5)
infix: A*(B+C*D)+E
postfix: ABCD*+*E+
6)
infix: A+(B*C-(D/E^F)*G)*H
postfix: ABC*DEF^/G*-H*+
7)
infix: (A+B)*C+D/(E+F*G)-H
postfix: AB+C*DEFG*+/+H-
8)
infix: A-B-C*(D+E/F-G)-H
postfix: AB-CDEF/+G-*-H-
*/
#include<stdio.h>
#include<stdlib.h>
//*******************************************
//** STACK
#define size 10
struct stack {
int count;
char stack[size];
} s;
void stack_push(char c) {
if (s.count < size) {
s.stack[s.count] = c;
s.count = s.count + 1;
}
}
char stack_pop() {
char item;
if (s.count > 0) {
s.count = s.count - 1;
item = s.stack[s.count];
}
return item;
}
int stack_isEmpty() {
return s.count == 0;
}
char stack_topChar() {
return s.stack[s.count - 1];
}
//*******************************************
//** Aux operations
int isOperand(char c) {
return c >= 'A' && c <= 'Z';
}
int isOperator(char c) {
char* operators = "+-*/^\0";
int result = 0;
for (int i = 0; operators[i] != '\0'; i++) {
if (operators[i] == c) {
result = 1;
break;
}
}
return result;
}
int getPrecedence(char c) {
int result = 0;
switch (c) {
case '^': result++;
case '/':
case '*': result++;
case '-':
case '+': result++;
}
return result;
}
//*******************************************
//** to Postfix
void toPostfix(char* expression) {
char* result;
int idx = 0;
for (int i = 0; expression[i] != '\0'; i++) {
char c = expression[i];
if (isOperand(c)) {
result[idx++] = c;
}
else if (isOperator(c)) {
char topChar;
while (1) {
topChar = stack_topChar();
if (stack_isEmpty() || topChar == '(') {
stack_push(c);
break;
}
else {
int precedenceC = getPrecedence(c);
int precedenceTC = getPrecedence(topChar);
if (precedenceC > precedenceTC) {
stack_push(c);
break;
}
else {
char cpop = stack_pop();
result[idx++] = cpop;
}
}
}
}
else if (c == '(') {
stack_push(c);
}
else if (c == ')') {
char cpop = stack_pop();
while (cpop != '(') {
result[idx++] = cpop;
cpop = stack_pop();
}
}
}
while (!stack_isEmpty()) {
char c = stack_pop();
result[idx++] = c;
}
result[idx] = '\0';
printf("%s", result);
}
//*******************************************
//** main
int main() {
printf("Insert expression: ");
char* expression;
char c;
int idx = 0;
do {
c = getchar();
if (c == '\n' || c == EOF)
c = '\0';
expression[idx++] = c;
} while (c != '\0');
toPostfix(expression);
return 0;
}
我已经尝试在Google上到处寻找解决方案,但没有找到任何解决方案,因此希望您能在这里为我提供帮助。
我遇到的错误可以在这里找到:https://imgur.com/a/nFheImb
此:
char *result;
将创建指向不确定位置的未初始化指针。它不会创建字符串。因此,使用result[idx++]
访问它会调用未定义的行为。
在您的情况下,您只想在本地使用字符串,最好创建一个固定大小的char缓冲区:
char result[80];
并且您必须确保不要写超过80个字符的字符串,在字符串末尾留空字符。
这只是解决您当前问题的快速解决方案。您应该研究数组,C字符串,指针和内存分配,以了解有关这些东西在C中如何工作的更多信息。