【发布时间】:2015-07-18 15:05:49
【问题描述】:
in = "(A + B) * C - D * F + C";
#define MAXL 256
我在case ')' 的代码有问题。
我的代码未完成,因为它在某处遗漏了几行代码,以将堆栈内的所有最终char = operators 添加到tempExp,我可能很快就会弄清楚™。我现在需要的是您输入为什么这条线while(c[0] != '(') strcat(tempExp, c); 会导致未定义的行为。
非常感谢!
注意:这个混乱的代码c[0] = *((char*)pop(s)) 的原因是pop 返回一个void*,我无法在本练习中更改它。
void convertIntoPost(char * in, char ** out)
{
int i;
Stack * s = createStack();
char tempExp[MAXL] = "temp: ", c[2];
c[1] = '\0';
printf("\n%s\n", tempExp);
for(i = 0; i <= strlen(in); ++i)
{
printf("i: %d", i);
c[0] = in[i];
if(isalpha(c[0]) || isalnum(c[0]))
{
c[0] = in[i];
printf("\nc passed isalpha OR isalnum: %s\n", c);
strcat(tempExp, c);
}
else
{
switch(in[i])
{
case ' ' : break;
case '(' :
push(s, &in[i]);
break;
case ')' :
c[0] = *((char*)pop(s));
printf("c in case ')': %s", c); /* Show expected result */
printf("\n%s", tempExp); /* Just checking tempExp and see no problem */
while(c[0] != '(')
strcat(tempExp, c);
printf("\n%s", tempExp); /* Program stopped before it gets here */
break;
default :
while(!isEmpty(s) && (priority(in[i]) <= priority(c[0] = *((char*)pop(s)))))
strcat(tempExp, c);
push(s, &in[i]);
}
}
}
printf("\nThis is in: %s", in);
printf("\n%s", tempExp);
*out = (char*)malloc(strlen(tempExp) + 1);
*out = strdup(tempExp);
makeEmpty(s);
}
int priority(char c)
{
if(c == '(')
return(0);
else if(c == '+' || c == '-')
return(1);
else if(c == '*' || c == '/')
return(2);
}
【问题讨论】:
-
你应该在那个循环中有条件
i <= strlen(in)吗?这将导致循环在in中包含字符串终止符。 -
while 永远不会运行,或者永远不会停止。
-
strcat(连续地)连接整个字符串c,而不仅仅是第一个字符。它也不会切断它c。看来您来自另一种语言。 -
@Pawan 他为什么要这么做?在 Mizushima:考虑删除 undefined behavior 标签。
-
@Joachim 我测试过,strlen 返回不包括终止符的字符串长度。这是来自另一个函数的
in的第三次传递,之前的 2 次传递没有使程序崩溃。