问题描述
我正在动态分配一个结构不同的结构作为成员:
I am dynamically allocating a struct which has a different struct as a member:
struct a {
// other members
struct b;
}
struct b
基本上持有指向另一个struct b
的指针,因此请将struct b
视为链接列表.
struct b
basically holds a pointer to another struct b
, so think of struct b
as a linked list.
如果我动态分配struct a
,那么这也会在其中分配一个新的struct b
.但是,这样做还是让struct a
持有指向struct b
的指针并在struct a
中动态分配struct b
之间有什么区别?实施上有什么区别?
If I dynamically allocate struct a
, then that would also make a new struct b
within it. However, what is the difference between doing that or having struct a
hold a pointer to struct b
, and dynamically allocate struct b
within struct a
? What is the difference in implementation?
推荐答案
如果您像这样动态分配(malloc)struct a
If you dynamically allocate (malloc) struct a
as in
struct a *temp = (struct a *)malloc(sizeof(struct a));
您在malloc
空间中放置了指向struct b
的指针(假设这是struct a
中的内容),但是您没有在malloc
空间中使用struct b
.这意味着以后您将不得不做
you malloc
space for a pointer to struct b
(assuming that's what is in struct a
) but you don't malloc
space for struct b
. That means later you'll have to do
temp->b = (struct b *)malloc(sizeof(struct b));
在尝试使用struct b
之前.
如果不存储指向struct b
的指针,而是直接存储struct b
的指针,则在定义struct a
时将获得自动分配.
If you don't store a pointer to struct b
but rather struct b
directly then you'll get the automatic allocation when you define struct a
.
这篇关于在结构内动态分配结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!