我正在尝试解析一个完全加括号的中缀表达式,并将其转换为一个后缀表达式,这样我就可以轻松地将表达式实现为二叉算术树。
这是我正在使用的示例字符串:((x2+5.14)*(3.41-5.00))
这是输出:
我试图打印出命令行中缀表达式的后缀表达式。 我几乎肯定这里存在内存泄漏,但我无法准确指出哪里出了问题。有人可以指出我的(很多)错误吗?
char *infixToPrefix(char *argString)
{
int i,j;
int popLoop = 1;
int length = strlen(argString);
char tempChar;
char tempString[5];
char *returnString = malloc(sizeof(char)*length);
Stack *opStack = createStack(length-1);
for(i=0;i<length-1;i++)
{
char *tempPop = malloc(sizeof(char)*5);
/* Character is a number; we assume a floating point in the form Y.XZ */
if(isdigit(argString[i]) > 0)
{
/* Take argString[i] and next three characters */
for(j=0; j<4; j++)
{
tempString[j] = argString[i];
i++;
}
i--;
tempString[4] = ' ';
returnString = strcat(returnString, tempString);
/* Recycle tempString by assigning first character to null pointer */
tempString[0] = '\0';
}
/* Character is variable; we assume the format is xY, where Y is an integer from 0-9 */
else if(argString[i] == 'x')
{
for(j=0; j<2; j++)
{
tempString[j] = argString[i];
i++;
}
i--;
tempString[2] = ' ';
returnString = strcat(returnString, tempString);
/* Recycle */
tempString[0] = '\0';
}
/* Character is binary operator; push on top of Operator Stack */
else if(argString[i] == '*' || argString[i] == '/' ||
argString[i] == '+' || argString[i] == '-')
{
tempString[0] = argString[i];
tempString[1] = '\0';
push(opStack,tempString);
tempString[0] = '\0';
}
/* Character is open parenthesis; push in top of Operator Stack */
else if(argString[i] == '(')
{
tempString[0] = argString[i];
tempString[1] = '\0';
push(opStack,tempString);
tempString[0] = '\0';
}
/* Character is closed parenthesis; pop Operator Stack until open parenthesis is popped */
else if(argString[i] == ')')
{
while(popLoop)
{
tempPop = pop(opStack);
tempChar = tempPop[0];
if(tempChar == '(')
{
free(tempPop);
popLoop = 0;
}
else
{
returnString = strcat(returnString, tempPop);
free(tempPop);
}
}
}
}
returnString = strcat(returnString, "\0");
return returnString;
}
最佳答案
各种问题
内存分配不足
// char *returnString = malloc(sizeof(char)*length); char *returnString = malloc(length+1);
无法附加
'\0'
。
strcat(returnString, "\0");
等同于strcat(returnString, "");
。 IAC,代码无法在returnString
上调用字符串函数,因为它还没有空字符终止,因此不是字符串。// returnString = strcat(returnString, "\0"); returnString[i] = '\0';
在 2 个地方,代码没有防止超出字符串末尾。
// for(j=0; j<4; j++) { for(j=0; argString[i]!='\0' && j<4; j++) { tempString[j] = argString[i]; i++; } // tempString[4] = ' '; tempString[j] = '\0';
tempPop
的使用在tempPop = pop(opStack);
中是可疑的。为什么代码还要向上分配它?也许其他人和
stack
没有声明,不能走得更远。
关于将中缀表达式转换为后缀表达式导致出现奇怪的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705398/