c - C中相互依赖的结构
问题描述
我正在关注 Ruslan Spivak 的文章系列/教程“让我们构建一个简单的解释器”,这是在 Python 中构建一个简单的 Pascal 解释器的指南。我正在尝试在 C 中跟进。我对添加抽象语法树的部分感到困惑。
我有这个头文件:
#include "tokens.h"
struct binopnode
{
struct node left;
token op;
struct node right;
};
struct node
{
union nvalue value;
enum ntype type;
};
enum ntype
{
NUM,
BINOP,
};
union nvalue
{
struct binopnode binop;
struct numnode num;
};
struct numnode
{
token tok;
};
其中"tokens.h"
包括token
typedef
'd 结构。
我的问题是我的编译器:
Apple clang version 12.0.5 (clang-1205.0.22.9)
Target: x86_64-apple-darwin20.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
抛出Incomplete Type
错误。
从这些链接:
http ://c-faq.com/decl/mutrefstructs.html
C 中的循环定义
我猜我必须使用指针,但我完全不知道在哪里。
解决方案
您可以先声明结构,然后再将它们作为指针引用。
在 C 中,当一个结构 A 包含另一个结构 B 时,A 将需要 B 大小的内存区域。如果结构 A 包含结构 B 而结构 B 包含结构 A,编译器无法决定应该为每个结构分配多少内存。因此,如果您想使用相互引用的结构,您应该至少使用其中一个作为指针。
#include "tokens.h"
struct binopnode;
struct node;
enum ntype;
union nvalue;
struct numnode;
struct binopnode
{
struct node *left;
token op;
struct node *right;
};
struct node
{
union nvalue *value;
enum ntype type;
};
enum ntype
{
NUM,
BINOP,
};
union nvalue
{
struct binopnode *binop;
struct numnode *num;
};
struct numnode
{
token tok;
};
推荐阅读
- javascript - CSS 动画后 CSS 元素意外重新出现
- java - 随机取一个字符串并将其放入堆栈?
- postgresql - Postgres fdw 使用外部触发器插入记录
- mysql - SQL中如何将数据拆分成不同的列
- javascript - 仅当我单击链接时出现 DataCloneError
- excel - 表之间的多重查找
- javascript - 行中的响应式等高元素
- python - 如何在 python 中尽可能快地发送 5000 个 JSON 请求?
- node.js - 如何使用 Nodejs Express 访问 Github Repo 中的数据
- python - 我如何使班级成员成为 Json 可序列化的