我正试图解析一个完全带圆括号的中缀表达式,并将其转换为后缀表达式,以便可以轻松地将该表达式实现为二进制算术树。
下面是一个我正在使用的字符串示例:((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';
在两种情况下,代码不能防止字符串末尾出现溢出。
// 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
没有声明,不能再进一步了。关于c - 将infix-expression转换为postfix-expression,导致显示奇怪的符号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26705398/