0

我正在制作这个非常简单的 lex 程序(只是一个介绍性程序)。但是在编译 lex.yy.c 时,我得到这个错误:

inToPostfix.l:26: error: ‘struct stackoperand’ has no member named ‘top’
inToPostfix.l:32: error: ‘struct stackoperator’ has no member named ‘top’....

因为我已经在指定的结构中定义了 top,所以我无法为这个错误提出任何理由。你能看出什么原因吗?

代码发布在http://pastebin.com/d5f059c1d

4

2 回答 2

2

这是与您的原始版本的差异。它修复了编译时的所有问题:

--- orig.l      2009-11-09 14:55:47.414002041 -0500
+++ kk.l        2009-11-09 14:54:53.386385539 -0500
@@ -1,14 +1,15 @@  
 %{
    #include<stdio.h>
 %}
+       int precedence(char a,char b);
        struct stackoperator{
                char stack[10];
-               int top =-1;
+               int top;
        };

        struct stackoperand{
                int stack[10][2];
-               int top =-1;
+               int top;
        };
        struct stackoperator operator;
        struct stackoperand operand;
@@ -29,6 +30,7 @@
        }
 [ \t]    ;
 [\n]      {
+               char ch;
                while(operator.top!=-1)
                {
                        ch=pop();
于 2009-11-09T19:59:13.013 回答
0

将第 3 行移至第 16 行。

您还需要从结构声明中删除初始化程序 - 至少对于 C(但 C++ 编译器也没有考虑太多)。

struct stackoperator
{
char stack[10];
int top =-1;
};

到:

struct stackoperator
{
char stack[10];
int top;
};

在动作中,您还需要声明“ch”。

您还需要声明您的函数 - 我将它们设为静态。这会编译(假设您有一个 C99 编译器 - 指定的初始化程序不适用于 C89 编译器):

%{
#include<stdio.h>

struct stackoperator
{
char stack[10];
int top;
};

struct stackoperand
{
int stack[10][2];
int top;
};
struct stackoperator operator = { .top = -1 };
struct stackoperand operand = { .top = -1 };
int num=0;
static void push(int num,int flag);
static int pop(void);
static int precedence(char a,char b);
%}

%%

[0-9]   {num=num*10+(*yytext-'0');push(num,1);}
[-+*/]  {
        if(precedence(operator.top,*yytext)) {
            char ch=pop();
            push(ch,0);
            operand.stack[operand.top][1]=1;
        }
        push(*yytext,0);
    }
[ \t]    ;
[\n]      {
        char ch;
        while(operator.top!=-1)
        {
            ch=pop();
            push(ch,0);
        }
        int i=0;
        while(i<=operand.top)
        {
            if(operand.stack[operand.top][1]==1)
                printf(" %c ",operand.stack[operand.top][0]);
            else
                printf(" %d ",operand.stack[operand.top][0]);
        }
    }
%%

static void push(int num,int flag)
{
    if(flag)
    {       operand.top++;
        operand.stack[operand.top][0]=num;
        operand.stack[operand.top][1]=0;
    }
    else
        operator.stack[++operator.top]=num;
}

static int pop(void)
{
    return operator.stack[operator.top--];
}

static int precedence(char a,char b)
{
    if(operator.top==-1)
        return 0;

    if((a=='*'||a=='/') && (b=='+'||b=='-'))
        return 1;
    else
        return 0;
}
于 2009-11-09T19:53:29.703 回答