gpt4 book ai didi

c - C 结构中的自引用

转载 作者:太空狗 更新时间:2023-10-29 16:53:06 24 4
gpt4 key购买 nike

K&R(C 书)的这一部分让我思考:

摘自本书:

struct tnode {
char *word;
int count;
struct tnode *left;
struct tnode *right;
};

节点的递归声明可能看起来很奇怪,但它是正确的。

因为 tnode 的定义不使用 tnode,而只是指向 tnode 的指针,编译器以某种方式给了我们免费通行证。但我想知道计算机如何知道在声明时给 tnode 多少内存?

最佳答案

指针具有固定大小(32/64 位,具体取决于平台),因此编译器知道左右指针需要多少内存,并可以计算结构的整体大小。

出于同样的原因,如果你需要一个指针,那么做一个前向声明就足够了 struct tnode; 你可以为该结构使用一个指针,例如:struct tree { struct tnode*根; };

关于c - C 结构中的自引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com