且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为联合分配内存以及联合指针和指针联合之间的区别

更新时间:2022-02-04 02:44:45

我认为您误解了指向工会的指针.

I think you are misunderstanding the pointer-to-union thing.

使用示例代码的一部分(您应该在问题正文中确实包含该代码)

Using a part of your example code (which you should really have in the question body)

union u1
{
    s1 a;
    s2 b;
};

那么就拥有

union u1 my_union;

您可以保证& my_union 等于& my_union.a & my_union.b .

关于

union u1 *u = malloc(sizeof(s1));
u->a.a = 3;
printf("s1.a=%d\n", u->a.a);
printf("s2.a=%d\n", u->b.a);

这仅能工作是因为两个原因:允许使用联合进行类型处理,并且 u-> aa u-> ba 完全相同大小和完全相同的位置.我的看法是,从技术上讲,它是UB,但由于其他要求而起作用.

This only works because of two reasons: Type-punning is allowed using unions, and both u->a.a and u->b.a are the exact same size and at the exact same position. The way I see it is that technically it's UB but works because of other requirements.

如果您尝试访问 u-&b; b.b ,则UB将得到保证.

If you attempted to access u->b.b the UB would be guaranteed.