当我试图编译我的代码中的yacc &法我得到这个错误: 使用yytext中野牛代码
的yacc代码:
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define YYSTYPE struct node*
typedef struct node{
char *token;
struct node *left;
struct node *right;
} node;
node* mknode(char* token, node *left, node *right);
void Printtree(node *tree);
int yyerror();
%}
%token NUM PLUS MINUS
%left PLUS MINUS
%%
S:exp {printf("OK\n"); Printtree($1);};
exp:exp PLUS exp {$$=mknode("+",$1,$3);}
| exp MINUS exp{$$=mknode("-",$1,$3);}
| NUM {$$=mknode(yytext, NULL, NULL);};
%%
#include "lex.yy.c"
int main(){
return yyparse();
}
node *mknode (char *token, node *left, node *right){
node *newnode = (node*)malloc(sizeof(node));
char *newstr = (char*)malloc(sizeof(token)+1);
strcpy (newstr, token);
newnode->left=left;
newnode->right=right;
newnode->token=newstr;
return newnode;
}
void Printtree(node* tree){
printf("%s\n", tree->token);
if (tree->left)
Printtree(tree->left);
if (tree->right)
Printtree(tree->right);
}
int yyerror(){
printf("ERROR\n");
return 0;
}
和法码
%%
[0-9]+ return NUM;
\+ return PLUS;
\- return MINUS;
%%
当我试图将yytext更改为$ 1时编译,但是当我运行代码并键入例如5 + 6时说:(segment fault(core dumped使用))
ubuntu的64:
法编译柔性版法2.6.0:
yacc subProject.yacc
:
lex subProject.lex
和yacc与野牛版本野牛(GNU野牛)3.0.4编译
和错误制造者:
cc subProject -o y.tab.c -ll -Ly
请勿在此发布文字链接或图片。发布文字。这是一个完全浪费你的时间,我不关心,我们的带宽,我做的。 – EJP
你实际上是在使用Bison的'yacc'吗?你从'yacc --version'得到什么?你真正使用的'lex'是Flex吗?你从'lex --version'得到什么?它可能很重要;原创的AT&T Yacc和Lex与Bison和Flex略有不同(并且请注意,此Flex的标签为[tag:flex-lexer]而非[tag:flex];另一个用于Adobe Flex)。 “yytext”的一种不同之处在于。但是,声明与否声明可能是一个单独的问题 - 除了使用正确的声明至关重要外。 –
我使用flex和bison编写了这个即时通讯,但现在我添加了这些版本。 –