gpt4 book ai didi

c - 结构中零长度数组的目的是什么?

转载 作者:IT老高 更新时间:2023-10-28 12:36:59 27 4
gpt4 key购买 nike

当我查看 Linux 内核代码时,发现以下代码:

   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”,它是一个零长度数组,它的用途是什么?提前致谢!

最佳答案

它是 C99 之前版本的灵活数组成员,由 GCC 作为扩展提供。

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

__u8  supervisor_stack[];

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

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

在 6.7.2.1 的第 18 段中,标准(草案 N1570)对它们进行了描述:

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.

关于c - 结构中零长度数组的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11733981/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com