灵活的数组成员在C-结构 [英] Flexible array member in C-structure
问题描述
从C-STD 6.7.2.1节引用,
Quoting from the C-std section 6.7.2.1,
struct s { int n; double d[]; };
这是一个有效的结构声明。我找了一些实际使用这种语法的。要precise,这是怎么构造的更多或更少的威力比保持双*作为第二个元素?或者,这是另一种情况友可以做它在多途径?
This is a valid structure declaration. I am looking for some practical use of this kind of syntax. To be precise, how is this construct any more or less powerful than keeping a double* as the 2nd element? Or is this another case of 'you-can-do-it-in-multiple-ways'?
Arpan
推荐答案
借助Ç常见问题解答答案precisely这个问题。快速的回答是,该结构将包括双
阵列的结构内,而不是一个指向结构之外的阵列。作为一个简单的例子,你可以在这个例子中使用结构为:
The C FAQ answers precisely this question. The quick answer is that this structure will include the double
array inside the structure rather than a pointer to an array outside the structure. As a quick example, you could use your structure as in this example:
struct s mystruct = malloc(sizeof(struct s) + 5 * sizeof(double));
s.n = 12;
s.d[0] = 4.0;
s.d[1] = 5.0;
s.d[2] = 6.0;
s.d[3] = 7.0;
s.d[4] = 8.0;
等等 - 你所关心的包括在分配,然后你可以使用它就像任何数组的数组的大小。通常这种类型包含大小结构的一部分,因为使用 +
诱骗通过键入取值$ C $数组跳过C>将这种情形并不复杂。
And so on - the size of the array you care about is included in the allocation, and then you can use it just like any array. Normally such a type contains the size as part of the structure, since using the +
trick to skip through an array of type s
will be necessarily complicated by this situation.
要你额外的问题,这是怎么建造任何比保持[指针]作为第二个元素或多或少厉害?,这是没有更多的强大的本身,而是你并不需要保持围绕指针,所以你会节省至少那么多的空间 - 还当你复制的结构,也将复制阵列,而不是一个指针数组 - 有时一个微妙的差异,但其他非常重要的时期。 友可以做它在多途径可能是一个很好的解释,但在有些情况下,你会特别想要一个设计案例或其他。
To your added question 'how is this construct any more or less powerful than keeping a [pointer] as the 2nd element?', it's no more powerful per se, but you don't need to keep a pointer around, so you would save at least that much space - also when you are copying the structure, you would also copy the array, rather than a pointer to an array - a subtle difference sometimes, but very important other times. 'You-can-do-it-in-multiple-ways' is probably a good explanation, but there are cases where you would specifically want one design or the other.
这篇关于灵活的数组成员在C-结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!