零长度数组 [英] zero length arrays
问题描述
最近我碰到一个结构定义来了,
Recently I came across a structure definition,
struct arr {
int cnt;
struct {
int size;
int *name;
} list[0];
};
,现在我不知道的原因列表[0]
正在申报。我所感兴趣的是,这是为什么使用。它有什么优势?如果有,是什么呢?
and now I don't know the reason for list[0]
being declared. What I am interested in is why is this used. Does it have any advantage? If yes, what is it?
推荐答案
使用是动态长度的数组。您可以使用分配内存的malloc()
,并有阵居住在该结构的末尾:
The use is for dynamic-length arrays. You can allocate the memory using malloc()
, and have the array reside at the end of the structure:
struct arr *my_arr = malloc(sizeof *my_arr + 17 * sizeof *my_arr->list);
my_arr->cnt = 17;
my_arr->list[0].size = 0;
my_arr->list[1].name = "foo";
实际上能够对长度使用0(如在注释中指出)一个GCC扩展。在C99,你可以离开了大小一共面值为同样的效果。
Actually being able to use 0 for the length is (as pointed out in a comment) a GCC extension. In C99, you can leave out the size literal altogether for the same effect.
在这些事情的顺利实施,你经常看到这个为1的长度做了,但分配复杂一点,因为你必须计算所需要的内存时补偿。
Before these things were implemented, you often saw this done with a length of 1, but that complicates the allocation a bit since you must compensate when computing the memory needed.
这篇关于零长度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!