gpt4 book ai didi

c - 灵活数组成员的偏移量是否会发生变化?

转载 作者:太空宇宙 更新时间:2023-11-04 04:37:47 25 4
gpt4 key购买 nike

标准 - §6.7.2.1.18 - 说

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.

问题是我不明白最后一条声明的标准含义。鉴于我们通常为灵活的数组成员以及其他成员留出足够的内存(使用 malloc()),怎么可能有非连续的偏移量?

最佳答案

它是说如果我们有:

struct A
{
int x;
int a[];
};

struct B
{
int x;
int b[20];
};

// ...
A *pa = malloc(sizeof(struct A) + sizeof(int[20]));
B *pb = malloc(sizeof(struct B));

然后 ptr->a 的行为与 ptr->b 完全一样,除了 offsetof(struct B, b)offsetof (struct A, a) 都是编译时常量,可能不同。

以下段落中有一些示例。

注意。在sizeof的作用下,它们的行为也有所不同,所以这段似乎有点瑕疵。

关于c - 灵活数组成员的偏移量是否会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29336835/

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