c++公用体union、结构体struct内存分配问题

#include<iostream>
#include<string>
#include<stdlib.h>

using namespace std;

union data
{
	char c1;     //字符型占1字节
	int n;       //整型占4字节
	double c2;   //公用体最大基础类型是double,8字节,以8对齐,
	char c3[9];  //字符数组占9字节 ,9>8,所以该公用体占8*2=16字节
};
union data1
{
	int b1;      //公用体最大基础类型是int,4字节,以4对齐
	char b2;
	char b3[9];   //字符数组占9字节 ,4*3=12字节
};
union data2
{
	char d1;    //公用体最大基础类型是char,1字节,以1对齐
	char d2[3]; //字符数组占3字节 ,1*3=3字节
};
struct data3
{
	char e1;   //公用体最大基础类型是char,1字节,以1对齐
	char e2[4]; //字符数组占4字节 ,1+4=5字节
};
struct data4
{
	//double f2;  //公用体最大基础类型是double,8字节,以8对齐
	//int f1;//16
	//double f4;
	char f2;
	double f4;   //与double位置有关,可测试不同位置的大小
	char f3;
	//double f4;
};
struct data6
{
	unsigned short i:4;
	unsigned short k:4;
	unsigned short j:8;  //共4+4+8=16位,实际共占32位,即4字节
	unsigned long t;     //公用体最大基础类型是unsigned long,4字节,以4对齐
	                     //输出8字节    
};
int main()
{
	int s;
	char q;

	int i=sizeof(data);  
	int j=sizeof(data1);  
	int k=sizeof(data2);
	int l=sizeof(data3);
	int m=sizeof(data4);
	int n=sizeof(data6);

	cout<<"int:"<<sizeof(s)<<endl;
	cout<<"char:"<<sizeof(q)<<endl;
	cout<<"union:data->"<<i<<endl;
	cout<<"union:data1->"<<j<<endl;
	cout<<"union:data2->"<<k<<endl;
	cout<<"struct:data3->"<<l<<endl;
	cout<<"struct:data4->"<<m<<endl;
	cout<<"struct:data4->"<<n<<endl;

	system("pause");
	return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值