共用体

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
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值