在结构内动态分配结构 [英] Dynamically Allocating a Struct within a Struct

查看:75
本文介绍了在结构内动态分配结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态分配一个结构不同的结构作为成员:

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.

这篇关于在结构内动态分配结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆