gpt4 book ai didi

c - 指向 union 成员的指针

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

我有一个结构:

struct TypeValue{
u8 type;
union{
u8 u8value;
s8 s8value;
}value;
}

根据 var 类型,我们可以从 u8values8value 中获取值。现在我有一个结构 TypeValue 并且我想获取指向 value 元素的 void 指针(不关心指针类型),哪个是正确的:

void *ptr = &typevalue.value (1)
OR
void *ptr = &typevalue.value.u8value (2)

(将其放入 for 循环中以根据类型找到正确的值)

当然 (2) 是正确的方法,但我必须遍历数据类型以获得指向正确值的正确指针。但问题是 (1) 是否正确,因为我想知道指向 union 的指针是否等于指向其元素的指针?big/little endian 会影响结果吗?

最佳答案

void *ptr = &typevalue.value 可以,因为 C 标准(N1570、6.7.2.1 结构和 union 说明符)说:

16 The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit- field, then to the unit in which it resides), and vice versa.

地址仅在当前运行环境中有意义(您不会将地址存储到闪存中),因此地址的字节顺序无关紧要。

关于c - 指向 union 成员的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24010052/

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