一个结构体中未定义的数组声明

为什么C允许这个:
typedef struct s
{
  int arr[];
} s;

数组arr没有指定大小?

解决方法

这是称为灵活阵列的C99功能,其主要特点是允许 answer to another question on flexible array members和07在这answer to another question on flexible array members中列出了使用灵活数组超过指针的好处.第6.7.2.1节结构和联盟规范第16段中的 draft C99 standard说:

As a special case,the last element of a structure with more than one named member may
have an incomplete array type; this is called a flexible array member. In most situations,
the flexible array member is ignored. In particular,the size of the structure is as if the
flexible array member were omitted except that it may have more trailing padding than
the omission would imply. […]

所以如果你有一个s *,那么除了结构体所需的空间之外,你还可以为数组分配空间,通常你会在结构中有其他成员:

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).

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...