struct 中的一个元素数组 [英] One element array in struct
本文介绍了struct 中的一个元素数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么有些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 with an flexible array member:
uint32 words[];
一些 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
.
Though for best results you should use size_t
instead of int
.
这篇关于struct 中的一个元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文