问题描述
为什么的 C 的允许这样的:
Why does C permit this:
typedef struct s
{
int arr[];
} s;
阵列改编
没有大小指定在哪里?
推荐答案
这是所谓的C99功能的灵活的阵列的,其主要特点是允许的提供的好处名单使用的灵活的阵列的过的指针的。该草案中部分 6.7.2.1
的结构和联合说明符的段落的 16 的说道:
This is C99 feature called flexible arrays, the main feature is to allow the use variable length array like features inside a struct and R.. in this answer to another question on flexible array members provides a list of benefits to using flexible arrays over pointers. The draft C99 standard in section 6.7.2.1
Structure and union specifiers paragraph 16 says:
作为一个特例,一个结构的一个以上的命名构件的最后一个元件可
有一个不完整的数组类型;这就是所谓的灵活数组成员。在大多数情况下,
柔性阵列构件被忽略。具体地,结构的尺寸是因为如果
除了灵活的阵列成员被省略,它可能有超过尾随填充
遗漏意味着。 [...]
所以,如果你有 A S *,你会为中的结构的,通常你会需要除了空间数组分配空间在结构上的其他成员:
So if you had a
s*
you would allocate space for the array in addition to space required for the struct, usually you would have other members in the structure:
s *s1 = malloc( sizeof(struct s) + n*sizeof(int) ) ;
标准草案实际上有第一个启发性的例子的 17 的:
EXAMPLE After the declaration:
struct s { int n; double d[]; };
the structure struct s has a flexible array member d. A typical way to use this
is:
int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));
and assuming that the call to malloc succeeds, the object pointed to by p
behaves, for most purposes, as if p had been declared as:
struct { int n; double d[m]; } *p;
(there are circumstances in which this equivalence is broken; in particular, the
offsets of member d might not be the same).
这篇关于在结构无浆数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!