gcc - 错误:取消引用指向不完整类型的指针

时间:2013-07-17 15:34:28

标签: c pointers struct unions dereference

我有一组相当复杂的嵌套结构/联合,如图所示:

typedef enum {
    expr_BooleanExpr,
    expr_ArithmeticExpr
} expr_type;

typedef union {
    struct BooleanExpr *_bool;
    struct ArithmeticExpr *_arith;
} u_expr;

typedef struct {
    expr_type type;
    u_expr *expr;
} Expression;

typedef struct {
    Expression *lhs;
    char *op;
    Expression *rhs;
} BooleanExpr;

typedef struct {
    Expression *lhs;
    char *op;
    Expression *rhs;
} ArithmeticExpr;

gcc很高兴我在其union字段中创建一个包含BoolExpression值的Expression结构,如下所示:

Expression *BooleanExpr_init(Expression *lhs, char *op, Expression *rhs) {

    BooleanExpr *_bool = safe_alloc(sizeof(BooleanExpr));
    _bool->lhs = lhs;
    _bool->op = op;
    _bool->rhs = rhs;

    Expression *the_exp = safe_alloc(sizeof(Expression));
    the_exp->type = expr_BooleanExpr;
    the_exp->expr->_bool = _bool;

    return the_exp;
}

虽然它会发出警告:从不兼容的指针类型[默认情况下启用] 为该行分配:the_exp->expr->_bool = _bool;

但是,在访问lhsrhs等内部表达式时,使用类似

的表达式
an_expr->expr->_bool->rhs

其中an_expr是以前创建的Expression结构,我得到了这篇文章标题中指定的错误。

我所阅读的大部分内容都表明,这是因为->运算符的使用需要.运算符。但是这是不合适的,因为一切都是指针,因此需要隐式取消引用->运算符。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您正在混合typedef个标识符和struct范围标识符。这不行。做点什么

typedef struct  BooleanExpr BooleanExpr;

在所有struct声明之前,仅将其作为

struct BooleanExpr { ...

没有typedef

在您的代码中,您从未定义过struct BooleanExp,但只定义了您对标识符struct进行别名的匿名BooleanExp