结构中未定义大小的数组声明 [英] Unsized array declaration in a struct

查看:74
本文介绍了结构中未定义大小的数组声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 C 允许这样做:

<前>typedef 结构体{int arr[];} s;

其中数组 arr 没有指定大小?

解决方案

这是 C99 的特性,叫做 flexible arrays,主要特性是允许 使用可变长度数组,如结构内的特征R..在这个关于灵活数组成员的另一个问题的答案 提供了使用灵活数组而不是的好处列表>指针.草案 C99 标准6.7.2.1 结构和联合说明符 段落 16 说:

<块引用>

作为一种特殊情况,具有多个命名成员的结构的最后一个元素可能有一个不完整的数组类型;这称为灵活数组成员.大多数情况下,灵活的数组成员被忽略.特别是,结构的大小就像灵活的数组成员被省略,除了它可能有更多的尾随填充比遗漏将意味着.[...]

因此,如果您有一个 s*,除了 struct 所需的空间外,您还需要为数组分配空间,通常结构中还有其他成员:

s *s1 = malloc( sizeof(struct s) + n*sizeof(int) ) ;

标准草案实际上在 17 段中有一个有启发性的例子:

<块引用>

示例声明后:

 struct s { int n;双 d[];};

结构struct s 有一个灵活的数组成员d.一个典型的使用方法是:

 int m =/* 一些值 */;struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

并假设对malloc的调用成功,p指向的对象在大多数情况下,行为就像 p 已声明为:

 struct { int n;双d[m];} *p;

(在某些情况下这种等价性被破坏;特别是成员 d 的偏移量可能不一样).

Why does C permit this:

typedef struct s
{
  int arr[];
} s;

where the array arr has no size specified?

解决方案

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:

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. [...]

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

the draft standard actually has a instructive example in paragraph 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).

这篇关于结构中未定义大小的数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆