1. 程式人生 > >c++ union內存

c++ union內存

printf print 存儲 -- 兩個 truct style union pan

看一個例子:

#include <iostream>
#include <stdio.h>
using namespace std;

union A {
    int a;
    struct {
        short b;
        short c;
    };
};

int main()
{
    A s;
    s.a = 0x12345678;

    printf("%x %x", s.b, s.c);
    return 0;
}

輸出結果:

5678 1234

為什麽是這樣的呢?

因為A是union,所以在內存中存儲的格式為:

高地址 ------------>   低地址

12     34    56    78

00010010 00110100 01010110 01111000

s.b 占據低地址的兩個字節

s.c 占據高地址的兩個字節

所以:

s.b = 5678

s.c = 1234

為了證明,以及看的更清楚,看下面這個程序。

#include <iostream>
#include <stdio.h>
using namespace std;

union A {
    int a;
    struct {
        short b;
        short c;
    };
};

int main() { A s; s.a = 0x12345678; printf("b = %x ; c = %x\n", s.b, s.c); printf("&a = %x ; &b = %x; &c = %x\n", &s.a, &s.b, &s.c); return 0; }

結果:

b = 5678 ; c = 1234
&a = 28ff1c ; &b = 28ff1c; &c = 28ff1e

是不是很明顯了。

c++ union內存