我正在尝试解析完全括号的中缀表达式并将其转换为后缀表达式,以便我可以轻松地将表达式实现到二进制算术树中。
以下是我使用的示例字符串: ((x2 + 5.14)*(3.41-5.00))
以下是输出:
我正在尝试打印出命令行infix-expression的postfix-expression。 我几乎肯定在这里有内存泄漏,但我无法准确指出出错的地方。有人能指出我的(很多)错误吗?
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;
}
答案 0 :(得分:2)
各种问题
内存分配不足
// 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
没有宣布,不能再进一步。