在一个结构元素的数组 [英] One element array in struct
本文介绍了在一个结构元素的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么有的结构采用单元素数组,如如下:
Why some struct uses a single element array, such as follows:
typedef struct Bitmapset
{
int nwords;
uint32 words[1];
} Bitmapset;
为了方便对后者的动态分配?
To make it convenient for latter dynamic allocation?
推荐答案
在一个字,是的。
基本上,C99的方式来做到这一点是:
Basically, the C99 way to do it is:
uint32 words[];
有些pre-C99编译器让你逃脱:
Some pre-C99 compilers let you get away with:
uint32 words[0];
但要保证它在所有的编译器的工作方式是:
But the way to guarantee it to work across all compilers is:
uint32 words[1];
然后,不管它是如何声明,你可以分配对象:
And then, no matter how it's declared, you can allocate the object with:
Bitmapset *allocate(int n)
{
Bitmapset *p = malloc(offsetof(Bitmapset, words) + n * sizeof(p->words[0]));
p->nwords = n;
return p;
}
虽然为达到最佳效果,你应该使用为size_t
而不是 INT
。
这篇关于在一个结构元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文