lex和yacc程序将中缀转换为前缀 [英] lex and yacc program to convert infix to prefix

查看:195
本文介绍了lex和yacc程序将中缀转换为前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是lex和yacc程序的新手.我一直试图编写一个yacc程序,该程序将一个算术表达式作为输入并以前缀表示法作为输出. 这是我的lex代码.

I am new to lex and yacc programs.I have been trying to write a yacc program which takes as input an arithmetic expression and gives prefix notation as output. here is my lex code.

%{
#include<string.h>
#include"pre.tab.h"
%}
%%
"*"|"/"|"+"|"-"|"("|")" {return yytext[0];}
[0-9]+ {yylval.name=(char*)malloc(yyleng+1);
   strcpy(yylval.name,yytext);
   return NUM;}
\n {return(0);}
[a-zA-Z][a-zA-Z]* {yylval.name=(char*)malloc(yyleng+1);
      strcpy(yylval.name,yytext);
      return ID;}
. {}
%%
int yywrap()
{
return 1;
}

这是我的YACC代码

%{
#include<stdio.h>
#include<string.h>
char buf[10];
%}

%union
{
  char *name;
}
%token<name>NUM ID
%type<name>E 
%left'+''-'
%left'*''/'
%nonassoc UMINUS
%%
S:E  {printf("\n%s",$1);}
;
E:E'*'E {buf[0]='\0';strcpy($$,strcat(strcpy(buf,"*"),strcat($1,$3)));}
|E'/'E {buf[0]='\0';strcpy($$,strcat(strcpy(buf,"/"),strcat($1,$3)));}
|E'+'E {buf[0]='\0';strcpy($$,strcat(strcpy(buf,"+"),strcat($1,$3)));}
|E'-'E {buf[0]='\0';strcpy($$,strcat(strcpy(buf,"-"),strcat($1,$3)));}
|ID
|NUM
|'('E')'{strcpy($$,$2);}
;
%%
main()
{
yyparse();
}
int yyerror(char *s) {fprintf(stderr,"%s\n",s);}

在括号中输入算术表达式时,我没有得到任何输出.例如:输入:1+(2 * 3)输出:+ * 23 * 23.我曾多次尝试纠正该代码,但徒劳无功.

I am not getting any output when I input an arithmetic expression in parantheses. Eg : Input : 1+(2*3) output : +*23*23. I have tried to rectify the code many times but in vain.

推荐答案

在C语言中,字符串不会像其他语言那样神奇地扩展. (或者,更好的说,实际上没有字符串对象.)除非您已经确保char数组a在NUL终止符之后有足够的空间来追加b,否则您不能调用strcat(a, b).

In C, strings do not magically expand like they do in other languages. (Or, better said, there really is no string object.) You cannot call strcat(a, b) unless you have already ensured that the char array a has enough space following the NUL terminator to append b.

您不能strcat使用字符串文字,因为不仅没有足够的空间,而且字符串文字也可能位于只读存储器中.

You can't strcat to a string literal, because not only is there not enough space, but also the string literal may be in read-only memory.

并且您不能strcpy到一个未分配的变量,并且期望有足够的内存自动分配. (尽管$$实际上不是未初始化的变量,因为它已被初始化为$1的值.)

And you can't strcpy to an unassigned variable and expect sufficient memory to be allocated automatically. (Although $$ is not actually an uninitialised variable, since it is initialised to the value of $1.)

因此您的代码充满了缓冲区溢出,这是未定义的行为.

So your code is full of buffer overruns, which is undefined behaviour.

这篇关于lex和yacc程序将中缀转换为前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆