gcc-错误:取消引用指向不完整类型的指针
我有一组相当复杂的嵌套结构/联合,如图所示:gcc-错误:取消引用指向不完整类型的指针,c,pointers,struct,unions,dereference,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; } Ex
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;
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;
}
gcc很乐意创建一个表达式结构,在其union字段中包含BoolExpression值,如图所示:
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;
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\u exp->expr->\u bool=\u bool代码>
但是,在访问内部表达式(如lhs
和rhs
)时
an_expr->expr->_bool->rhs
如果an_expr
是以前创建的表达式结构,我会得到本文标题中指定的错误
我读到的大部分内容都说,这是由于在需要
操作符的地方使用了->
操作符造成的。但是,这是不合适的,因为所有内容都是指针,因此需要->
运算符的隐式解引用
有什么想法吗?您正在混合typedef
标识符和struct
范围标识符。这不行。做点像
typedef struct BooleanExpr BooleanExpr;
在所有struct
声明之前,仅将它们作为
struct BooleanExpr { ...
没有typedef
在您的代码中,您从未定义过struct BooleanExp
,而只定义了一个匿名的struct
,您将它作为标识符BooleanExp
的别名,我认为在声明中添加strctBooleanExpr*\u bool=safe\u alloc(
应该是struct BooleanExpr*\u bool=safe\u alloc(
,试试这个,你可能会得到不同的错误。我试过这个,它会导致后面的语句:\u bool->lhs=lhs;\u bool->op=op;\u bool->rhs=rhs;
给出错误:取消对不完整类型的引用指针不要使用像\u bool
或\u arith
这样的标识符东西,它们是为实现保留的。啊,好的,谢谢你的头-up@AlexJ136正如我所说的,我意识到了这一点。:),你得到了下面的答案。