1、共用体存储空间大小
union un2
{
int i;
double y;
};
struct st
{
char a[10]; //10
union un2 b; //8
};
cout<<dec<<sizeof(struct st)<<endl; //按十进制输出 24
2、共用体数据公用内存空间实例(地位低地址,高位高地址)
union un
{
short int a;
char c[2];
}w;
w.c[0]='A'; w.c[1]='a';
cout<<hex<<w.a<<endl; //按十六进制输出,高字节为a,低字节为A 01100001 01000001=6141
#include "stdafx.h"
#include <iostream.h>
#include <string.h>
union
{
int i;
char x[2];
}a;
void main()
{
a.x[0] = 10; //低八位为00001010
a.x[1] = 1; //8~16位为00000001
printf("%d\n",a.i); //i在内存中00000000 00000000 00000001 00001010 = 266
}
#include "stdafx.h"
#include <iostream.h>
#include "string.h"
#include <memory.h>
typedef struct AA
{
int b1:5;
int b2:2;
}AA;
void main()
{
AA aa; //sizeof(AA) = 4
char cc[100];
strcpy(cc,"0123456789abcdefghijklmnopqrstuvwxyz");
memcpy(&aa,cc,sizeof(AA)); //将cc的前四个字节0、1、2、3的ASCII(48、49、50、51)放在aa
cout << aa.b1 <<endl; //低地址10000 = -16
cout << aa.b2 <<endl; //高低址001 = 1
//0的ASCII码为48 = 00110000 b1取低5位10000,b2取高3位001
}