2

yacc で 2 つの文字列を連結する方法がわかりません。

レックスコードはこちら

%{
#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];}

そして、ここに2つの文字列を追加するための基本があります

%{
#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();
}    

コードは機能します。問題は、出力が次のようになることです。

あああ+bbbb

私は出力を得る

あああ+bbbbbbbb

4

2 に答える 2

3

問題はここにあります:

yylval.strval = yytext;

yytext はすべてのトークンとすべてのバッファで変化します。に変更します

yylval.strval = strdup(yytext);
于 2013-01-22T01:59:24.370 に答える
1

yytextレクサーが次のトークンの検索を開始するまでのみ有効です。したがって、(f)lex から yacc/bison に文字列トークンを渡したい場合は、それを行う必要がstrdupあり、パーサー コードはコピーを解放する必要があります。

バイソンFAQ を参照してください。

于 2013-01-22T01:56:20.993 に答える