在 C 中获取工会成员的地址是否合法? [英] is it legal to take the address of an union member in C?

查看:26
本文介绍了在 C 中获取工会成员的地址是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

union U {
    int i;
    double d;
};

void foo (double *d) { *d = 3.4; }

int main ()
{
     union U u;
     foo (&(u.d));
}

gcc 没有抱怨(使用 -Wall -Wextra)并且它按预期工作,但我想确保它实际上是合法的(根据标准).

gcc does not complain (with -Wall -Wextra) and it works as expected, but I would like to make sure it is actually legal (according to the standard).

推荐答案

为什么不应该合法?实际上,甚至可以保证每个成员的地址等于整个联合的地址:

Why shouldn't it be legal? Actually, it's even guaranteed that the addresses of every member is equal to the address of whole union:

一个指向联合对象的指针,经过适当的转换,指向它的每个成员[...],反之亦然.

A pointer to a union object, suitably converted, points to each of its members [...] and vice versa.

(C11, §6.7.2.1 16)

(C11, §6.7.2.1 16)

(这意味着您可以获取一个指向联合成员的指针)

(which implies that you can take a pointer to union members)

这篇关于在 C 中获取工会成员的地址是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆