更改结构中的另一个值后更改char数组长度

时间:2015-04-26 16:56:19

标签: c++ parsing unions

所以我在这里遇到了一个奇怪的情况。

我正在尝试编写一个可以解析布尔表达式和逻辑表达式的程序,例如:(salary * 2> 10000)AND gender ='M'。

我使用了一个名为Node的结构来根据这里http://en.wikipedia.org/wiki/Syntax_diagram的概念来表示不同级别的每个操作。

我的节点构造

class Node {

int type;
union
{
    int i;
    double f;
    char c[LINESIZE];

    char buf[LINESIZE];

    char tname[LINESIZE];
    char attr[LINESIZE];

    struct Node *p[2];  // points to operands of an expression;
    struct Node *q; //
} value;

bool eval_b();
Node* eval_e();
Node* eval_t();
Node* eval_f();
};

value.buf存储实际表达式。

enode = T(E_ptr); // Create a TERM Node and parse the next token

if(enode == NULL){
    cout << "Error: T() returns NULL" <<endl;
    return(NULL);
}

while(token_type == '+' || token_type == '-'  )
{
    E_ptr = exp_p; //Move the pointer in the input

    flag++;

    // Initialize a node
    op = (struct Node *) malloc(sizeof(struct Node));

    strcat(op->value.buf, enode->value.buf);

    size_t len;
    if(token_type == '+'){

        op->type = ADD;
        strcat(op->value.buf, " + ");

        // The first len here!!!
        len = strlen(op->value.buf);
        cout << "after + , the len is:" << len << endl;
    }
    else if(token_type == '-'){
        op->type = MINUS;

        strcat(op->value.buf, " - ");
    }

    op->value.p[0] = enode;

    // The second len here!!!
    len = strlen(op->value.buf);
    cout << "before parsing + right , the len is:" << len << endl;

    op->value.p[1] = T(E_ptr);

    strcat(op->value.buf, op->value.p[1]->value.buf);

    if (op->value.p[1] == NULL){
        cout <<"Error: Some expression is expected after '+' or '-'." << endl;
        free(op);
        return(NULL);
    }
    operand = op;
}

if(flag == 0){
    op = (struct Node *) malloc(sizeof(struct Node));
    op->type = EXPRESSION;
    op->value.q = enode;
    strcpy(op->value.buf, enode->value.buf);
    operand = op;
}

return operand;

我的输入是身高+ 0.3&gt; 2.0 len可以产生良好的长度,即9.(“高度+”) 但是在我将enode传递给op-&gt; value.p [0]后,len减少到3。当我把它打印出来时,就会变成“ A ”。

这里出了什么问题?

0 个答案:

没有答案
相关问题