说我有
struct node {
struct example *left;
struct example *right;
int whatever;
};
struct example {
struct example *foo;
struct example *bar;
}
现在当我这样做的时候
struct node *example_node = malloc(sizeof(struct node));
要初始化我的节点结构,这个malloc实际做什么?我知道它应该分配内存,这样示例节点就可以指向某个地址,该地址包含足够的字节来容纳整个结构节点。。。。但是什么是开放的呢?
它是
a)有足够的空间启动结构的空白模板
b)struct节点内部的两个结构是否也已启动?所以我可以开始做一些像example-node->left->foo这样的事情吗?
c)左右侧的struct example*foo是否也已启动?
我只是搞不清我能得到什么,我需要什么自由,等等。
最佳答案
考虑一下这个sizeof(struct node)
给出node
结构的大小malloc( N )
从内存分配N个字节
因此malloc(sizeof(struct node))
至少分配存储struct node
所需的字节数。
结构内部node
struct example *left;
struct example *right;
int whatever;
这是指向结构
example
的两个指针和一个整数。因此,分配的内存空间足够大,可以包含这两个指针和一个
int
。不是整个结构,只是指针。为了完成分配,您可能还需要分配这两个内部结构,比如
struct node *example_node = malloc(sizeof(struct node));
example_node->left = malloc(sizeof(struct example));
example_node->right = malloc(sizeof(struct example));
你以相反的顺序释放这些分配,
开始释放
example
和left
然后释放
right
结构你一有空就没空了。这可能有用,但这是未定义的行为。
因此,如果首先释放
node
,就无法可靠地访问依赖于node
(在内部)的left
和right
成员。free (example_node->left);
free (example_node->right);
free (example_node);
关于c - 在C中分配一个具有结构作为元素的结构?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55506756/