C结构,指向结构的联合指针 [英] C struct, union pointer to struct

查看:50
本文介绍了C结构,指向结构的联合指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个typedeffed结构和一个并集.联合包含该结构和一个 uint32_t .目标是为 foo 分配一个与该结构中的位"相对应的值.

I have a typedeffed struct and an union. The union contains the struct and a single uint32_t. The goal is to assign a value to foo that corresponds to the 'bits' in the struct.

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

typedef struct {
    uint32_t valA :1;
    uint32_t valB :1;
    uint32_t valC :1;
    uint32_t valD :1;
    uint32_t valE :1;
} ValStruct_Type;

typedef union {
    ValStruct_Type valStruct;
    uint32_t valUint;
} ValUnion_Type;

uint32_t foo = 0;


int main(void)
{
    ValStruct_Type Vals;
    Vals.valA = 0x0;
    Vals.valB = 0x1;
    Vals.valC = 0x0;
    Vals.valD = 0x1;
    Vals.valE = 0x1;

    ValStruct_Type *Vals_ptr;
    Vals_ptr = &Vals;

    foo = ((ValUnion_Type *)Vals_ptr)->valUint;

    return 0;
}

foo变为:

Decimal:    4194330
Hex:        0x40001a
Binary:     10000000000000000011010

谁能确切解释这里发生了什么(指向结构指针的联合指针,被递归给工会成员的东西?)?

Who can explain what is happening here exactly (union pointer to a struct pointer, defererenced to a union member?)?

第二:为什么除了1、3和4位以外,还要设置 foo 的22位?

Secondly: why is bit 22 of foo set in addition to bit 1,3 and 4?

推荐答案

由于未定义的行为,设置了位22.您已经创建了一个从未完全初始化的局部变量,然后将其设置为5位.剩下的位就是它们碰巧的样子,未初始化的本地变量就是这种情况.

Bit 22 is set due to undefined behavior. You've created a local variable that you never fully initialized, and you then set 5 bits of it. The remaining bits are whatever they happen to be, which is the case with uninitialized locals.

关于您问题的第一部分...还有什么不清楚的地方?您的问题(指向结构指针的 union指针,被推迟为工会成员的)似乎可以回答自己.将某些内容强制转换为现有类型无效.

Regarding the first part of your question... what isn't clear? Your question (union pointer to a struct pointer, defererenced to a union member) seems to answer itself. Casting something to the type it already is doesn't have any effect.

这篇关于C结构,指向结构的联合指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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