结构体中数组和结构体的 Malloc
一个如何 malloc 一个位于另一个结构内部的结构?
我还想在结构内分配一个项目数组,然后在需要时重新分配该数组,这是如何正确完成的?
您能否给出一个声明结构的示例,然后是上面的内容。
我有点不确定事情的顺序。
结构体中的数组是否会被释放,然后结构体本身是否会被释放?结构体在创建时是否必须进行 malloc,然后对其字段进行 malloc/声明等?
How does one malloc a struct which is inside another struct?
I would also like to malloc an array of items inside a struct and then realloc this array when needed, how is this done correctly?
Could you please give an example of declaring a struct and then the above.
Im a little unsure of the order of things.
Would the array within a struct be freed and then the struct itself, must the struct be malloced when it is created and then its fields be malloced/declared etc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
包含在另一个
struct
内的struct
是通过副本包含的,因此您不必单独对其进行 malloc。如果struct
包含指向另一个struct
的指针,那么您可以考虑为其动态分配内存。在
struct Rect
中,struct Point2D
元素被插入到struct Rect
中,您不必为它们动态分配内存。相反,在 struct LinkedListNode 中,下一个元素由指针引用,并且必须动态分配内存。两个版本都有用,看情况。管理内存没有正确的方法,这取决于您的使用情况。
同样的情况也发生在数组的情况下。如果您的数组是静态大小的,那么它可以直接包含在
struct
中。但是,如果大小可能变化,则必须在struct
中存储一个指针。realloc函数只进行浅拷贝,即复制指针值,但不复制指向的对象。再说一次,你如何处理它取决于你的应用程序。
A
struct
included inside anotherstruct
is contained by copy, so you would not have to separately malloc it. If thestruct
contains a pointer to anotherstruct
, then you can consider allocating memory for it dynamically.In
struct Rect
, thestruct Point2D
element are inserted intostruct Rect
and you don't have to dynamically allocate memory for them. On the contrary in thestruct LinkedListNode
the next element is referenced by a pointer and the memory must be dynamically allocated.The two version are both useful, depending on the situation. There is no correct way to manage memory, it'll depend on your usage.
This same situation occurs in the case of an array. If your array is statically sized, then it can be directly included in the
struct
. However, if the size can vary, you must store a pointer within thestruct
.The
realloc
function only does a shallow copy, that is pointer value is copied, but not the pointed object. One more time, how you deal with it will depend on your application.以下是结构体中嵌套结构体和数组的示例。您会注意到在
释放
外部结构之前必须如何处理嵌套元素,否则最终会导致内存泄漏。The following is an example of nested structs and arrays in structs. You'll notice how the nested elements must be taken care of before you
free
the outer struct or else you'll end up with a memory leak.它的可读性不是很好,但有时人们会创建一个带有计数成员和最终单元素数组成员的结构。然后有一个特殊的工厂方法,它分配足够的空间,以便您可以写入对数组中的元素进行计数。显然数组成员可以是任何类型。
It's not very readable but sometimes people create a structure with a count member and a final single-element array member. There then is a special factory method that allocates enough space so that you can write to count elements in the array. Obviously the array member can be of any type.
获取单个 B:
获取 B 数组:
To get a single B:
To get an array of B: