Heim  >  Fragen und Antworten  >  Hauptteil

c++ - Wozu dient Union in der C-Sprache?

RT, die letzte Zuweisung dieser Struktur überschreibt die vorherige Zuweisung, daher bin ich gespannt, in welchen Szenarien so etwas im Allgemeinen verwendet wird?

世界只因有你世界只因有你2658 Tage vor995

Antworte allen(5)Ich werde antworten

  • 漂亮男人

    漂亮男人2017-06-12 09:26:44

    省内存,方便取高低字节

    Antwort
    0
  • 某草草

    某草草2017-06-12 09:26:44

    最初目的就是为了节省内存,你想当初C语言在上个世纪八十年代才开始大规模使用,那时的内存很宝贵的。

    Antwort
    0
  • ringa_lee

    ringa_lee2017-06-12 09:26:44

    可以提供对同一段数据不同的访问接口。。。
    举个例子,曾经做嵌入式的时候,可以这样写:

    // 没有字节对齐,或者字节对齐为1,int 占4字节
    typedef union {
        unsigined int num;
        struct {
            unsigned char byte0;
            unsigned char byte1;
            unsigned char byte2;
            unsigned char byte3;
        } bytes;
    } Demo;

    不过这样写也不太简洁,而且这段代码在 PC 里面和直接通过位移取每一个字节效率是一样的。只是举个例子,不要太纠结。

    Antwort
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-12 09:26:44

    一般用来判断大小端

    Antwort
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-12 09:26:44

    在嵌入式开发中用的比较多,我这里给个例子,和上面 @zonxin 的差不多

    typedef struct __regular_descriptor_4_high {
        union {
            U32 value;
            struct {
                U32 raid_id0    : 4;
                U32 raid_cmd0   : 4;
                U32 raid_id1    : 4;
                U32 raid_cmd1   : 4;
                U32 raid_id2    : 4;
                U32 raid_cmd2   : 4;
                U32 raid_id3    : 4;
                U32 raid_cmd3   : 4;
            } reg_des_bit;   
        } u; 
    } reg_des_4_high;

    要读取整个寄存器可以读value,要写不同的bit-filed就用reg_des_bit来写。

    Antwort
    0
  • StornierenAntwort