gpt4 book ai didi

c - 为什么我不能检索我的灵活数组成员大小?

转载 作者:太空狗 更新时间:2023-10-29 15:15:50 26 4
gpt4 key购买 nike

好的,所以我正在阅读标准论文 (ISO C11) 中解释灵活数组成员的部分(在 6.7.2.1 p18)。它是这样说的:

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.

下面是一些示例 (p20):

示例 2 声明之后:


struct s { int n; double d[]; };
结构 struct s 有一个灵活的数组成员 d。一个典型的方法 使用这个是:

int m = /* some value */;
<br/>
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));
并假设对 malloc 的调用成功,指向的对象 在大多数情况下,p 的行为就好像 p 已被声明为:

struct { int n; double d[m]; } *p;
(在某些情况下,这种等价性会被打破;在 特别是,成员 d 的偏移量可能不相同)。

在标准中作为示例添加的剧透不是文档。

现在我的示例(从标准扩展):

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
struct s { int n; double d[]; };

int m = 7;

struct s *p = malloc(sizeof (struct s) + sizeof (double [m])); //create our object

printf("%zu", sizeof(p->d)); //retrieve the size of the flexible array member

free(p); //free out object
}

在线example .

现在编译器提示 p->d 的类型 double[] 不完整,根据标准文件显然不是这种情况。这是 GCC 编译器中的错误吗?

最佳答案

As a special case, the last element of a structure with more than one named member may have an incomplete array type; ... C11dr 6.7.2.1 18

下面的d是一个不完整的类型。

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

The sizeof operator shall not be applied to an expression that has function type or an incomplete type ... C11dr §6.5.3.4 1

// This does not change the type of field `m`.
// It (that is `d`) behaves like a `double d[m]`, but it is still an incomplete type.
struct s *p = foo();

// UB
printf("%zu", sizeof(p->d));

关于c - 为什么我不能检索我的灵活数组成员大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38642564/

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