什么是一个结构一个零长度数组的目的是什么? [英] What is the purpose of a zero length array in a struct?

查看:94
本文介绍了什么是一个结构一个零长度数组的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在寻找Linux内核code,发现下面的code:

When I'm looking the Linux kernel code, found the below code:

   struct thread_info {
    struct task_struct  *task;
    struct exec_domain  *exec_domain;
    unsigned long       flags;
    __u32           status;
    __u32           cpu;
    int         preempt_count;
    mm_segment_t        addr_limit;
    struct restart_block    restart_block;
    void __user     *sysenter_return;
    unsigned long           previous_esp;
    __u8            supervisor_stack[0];
};

请注意,最后一个变量supervisor_stack,它是一个零长度的数组,什么是它的使用情况如何?在此先感谢!

Notice that the last variable "supervisor_stack", it is a zero length array, what is the usage of it? Thanks in advance!

推荐答案

这是一个灵活的阵列成员,通过GCC提供作为扩展的pre-C99版。

It's the pre-C99 version of a flexible array member, offered by gcc as an extension.

C99的办法就是用空的方括号定义灵活数组成员,

The C99 way is to define the flexible array member with empty brackets,

__u8  supervisor_stack[];

它用于存储数据的量不是恒定的邻接的结构体。内存形式分配

It's used to store data whose amount is not constant contiguous to the struct. Memory is allocated in the form

struct foo *ptr = malloc(sizeof *ptr + whatever_is_needed);

在段6.7.2.1 18,日标(N1570草案)描述他们:

In paragraph 18 of 6.7.2.1, the standard (draft N1570) describes them:

作为一个特例,一个结构的一个以上的命名构件的最后一个元件可
  有一个不完整的数组类型;这就是所谓的灵活的数组成员。在大多数情况下,
  在灵活的阵列成员被忽略。具体地,结构的尺寸是因为如果
  除了灵活的阵列成员被省略,它可能有超过尾随填充
  遗漏意味着。然而,当一个。 (或 - >)运算符具有左操作数是
  (指针)具有灵活的阵列成员和正确的操作名称的结构
  部件,它的行为就好像该构件用最长阵列代替(具有相同的
  元素类型),不会使结构不是被访问的对象大;该
  阵列的偏移应保持灵活的阵列成员的,即使这将不同
  从更换阵列。如果这个数组就没有的元素,它的行为就好像
  它有一个元素,但如果任何试图访问该理解过程网络连接定义的行为
  元素或以产生的指针1过去它

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. However, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.

这篇关于什么是一个结构一个零长度数组的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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