gpt4 book ai didi

可以将 union 内的对齐结构强制转换为 union 以访问对齐字段吗?

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:35 26 4
gpt4 key购买 nike

我想弄清楚你从 C99 中对齐变量的地役权中得到了什么:

Exception to strict aliasing rule in C from 6.5.2.3 Structure and union members

如果原始写入是通过指向如下所示对齐结构之一的指针完成的,它是否让您全权转换到该 union ?

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

struct Foo { char t; int i; };

struct Bar { char t; float f; };

union FooBar {
struct Foo foo;
struct Bar bar;
};

void detector(union FooBar *foobar) {
if (((struct Foo*)foobar)->t == 'F')
printf("Foo %d\n", ((struct Foo*)foobar)->i);
else
printf("Bar %f\n", ((struct Bar*)foobar)->f);
}

int main() {
struct Foo *foo = (struct Foo*)malloc(sizeof(struct Foo));
struct Bar *bar = (struct Bar*)malloc(sizeof(struct Bar));

foo->t = 'F';
foo->i = 1020;
detector((union FooBar*)foo);

bar->t = 'B';
bar->f = 3.04;
detector((union FooBar*)bar);

return 0;
}

请注意,在第二次调用中,t 被写为 “bar's t” 但随后为了辨别它属于哪种类型,检测器将其读取为 < em>“foo's t”

我对 C++ 的 react 是,只有“首先将它分配为 FooBar union ”,你才能做到这一点。认为这是合法的对我来说是违反直觉的,但对于 C 中的动态分配,没有这样的事情。因此,如果您不能这样做,那么在此异常下,您究竟可以使用上述动态内存分配做什么?

最佳答案

如果你做了这样的事情:

struct Foo foo;
struct Bar bar;
...
detector((union FooBar*)&foo);
detector((union FooBar*)&bar);

然后您可能会遇到对齐问题,因为编译器可能会将这些结构中的每一个以一种可能无法正确对齐另一个的方式放置在堆栈上。

但是因为在您的情况下您是为每个结构动态分配内存,所以对齐不是问题。

来自 malloc 的手册页:

For calloc() and malloc(), the value returned is a pointer to the allocated memory, which is suitably aligned for any kind of variable, or NULL if the request fails.

但是如果您想确保这不会成为问题,只需在调用期望 union 的函数的任何地方声明 union 的实例而不是包含结构。

关于可以将 union 内的对齐结构强制转换为 union 以访问对齐字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33917674/

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