在yacc中连接字符串

时间:2013-01-22 01:45:10

标签: c bison yacc flex-lexer

我似乎无法弄清楚如何在yacc中连接两个字符串。

这是lex代码

%{
#include <stdio.h>
#include "y.tab.h"
%}
%%
[0-9]+ {yylval.intval=atoi(yytext); return NR;}
[a-zA-Z]+ {yylval.strval=yytext; return STR;}
"0exit" {return 0;}
[ \t] ;
\n {return 0;}
. {return yytext[0];}

这里我有基础知识来添加两个字符串

%{
#include <stdio.h>
#include <string.h>
%}
%union {
int intval;
char* strval;
}
%token STR NR
%type <intval>NR
%type <strval>STR
%type <strval>operatie
%left '+' '-'
%right '='
%start S
%%
S   : S operatie        {}
    | operatie          {printf("%s\n",$<strval>$);}
    ;

operatie    :   STR '+' STR {   char* s=malloc(sizeof(char)*(strlen($1)+strlen($3)+1));
                                strcpy(s,$1); strcat(s,$3);
                                $$=s;}
            ;
%%
int main(){
 yyparse();
}    

代码有效,问题是输出是这样的: 如果我输入

  

aaaa + bbbb

我得到了输出

  

aaaa + bbbbbbbb

2 个答案:

答案 0 :(得分:2)

问题在于:

yylval.strval = yytext;

yytext随每个令牌和每个缓冲区而变化。将其更改为

yylval.strval = strdup(yytext);

答案 1 :(得分:1)

yytext仅在词法分析器开始寻找下一个标记之前有效。因此,如果要将字符串标记从(f)lex传递给yacc / bison,则需要strdup,并且解析器代码需要释放副本。

请参阅bison faq

相关问题