我目前没有代码,因为我根本不知道怎么做。我可以自己计算每个低级结构需要多少字节,并将它malloc到它?这真是可怕的编码,不是吗。这是我试图混在一起的两个结构:
struct property {
int d;
char name [111]; // I just malloc this like I would a normal array, right?
char descr [1025]; // Ditto.
}
struct category {
int d [413]; // The d's of all the child structs sorted highest to lowest.
char name [111];
struct property property [413]; // This. How do I allocate this?
}</code>
我必须struct property* property = (struct property*) malloc(sizeof(struct property) * 413);
吗?阵列内的malloc是否仍然完好无损?结构中的malloc如何表现一般?
答案 0 :(得分:4)
您的结构property
内没有指针成员,因此您不需要malloc
任何结构成员。
当你malloc
为结构时它会给你足够的内存来容纳包括数组在内的所有结构成员,异常是指针结构成员(你没有任何)。
答案 1 :(得分:3)
没有演员的malloc
会很好。它为整个数组分配连续的内存。结构体内的数组都与它一起分配,它们是正确的数组而不是指针。
答案 2 :(得分:2)
Sizeof将为您提供整个结构的大小。它恰当地说明了数组和结构的大小。
然而,413项似乎是随意的。可变大小的结构会更适合您吗?
在这种情况下,提前计算大小以避免mallocs是一个很好的性能想法。 Malloc可能很慢,它可能需要锁定,并且堆可能会随着时间的推移而碎片化。此示例向您展示如何在结构的末尾使用指针而不是数组或可变长度数组创建“可变长度”结构:
struct category
{
int cItems; // need this if handling variable # of items now.
int *d; // ptr instead of array
char *name; // ptr again
struct property property[0]; // var length array
}
int cItems = 413; // or whatever
// this is a nifty trick to get the size of a variable length struct:
int cbCategory = (size_t)(&((struct category*)0)->property[cItems]);
int cbD = sizeof(int)*cItems;
int cbName = sizeof(char)*cItems;
struct category *pCategory = (struct category*)malloc(cbCategory + cbD + cbName);
// wire up d:
pCategory->d = (int*)((char*)pCategory + cbCategory);
// or wire d up this way:
pCategory->d = (int*)&pCategory->property[cItems];
// wire up name
pCategory->name = (char*)pCategory->d + cbD;
// or wire up name this way
pCategory->name = (char*)&pCategory->d[cItems];
// set items
pCategory->cItems = cItems;
注意,我假设d有413个元素。我可以很容易地把它留下一个数组。