c++一些数据结构占用空间大小的判断

#ifndef _TEST_H
#define _TEST_H
#include <iostream>
#include <string>
using namespace std;

//这三种数据类型使用方式相似,都是使用成员对象操作符对成员进行操作。
//如:test_struct ts; ts.f=10;
//test_enum te; te=RED
//test_union tu; tu.ch="hello"
struct test_struct
{
	short int c;
	int f;
	char ch[17];//这个字节对齐的时候是按照char的长度进行对齐
};

enum test_enum
{
	RED,
	BLUE,
	GREEN,
};

//节省空间,所有成员都是公用一个起始地址
union test_union
{
	test_union(){};
	char a;
	int b;
	double c;
	short int d;
	char ch[100];
};

void main()
{
	//注意:数据类型都是说几个机器字长,如int是一个机器字长,如果在32
	//位(x86)的机器上就是4个字节,而在64位(x86_64)的机器上就是4字节
	//其他的数据也是如此
	cout << sizeof(int) << endl;
	cout << sizeof(double) << endl;
	cout << sizeof(long) << endl;
	cout << sizeof(long long) << endl;
	cout << sizeof(char [10]) << endl;
	cout << sizeof(int &) << endl;
	cout << sizeof(double &) << endl;

	//注意c++的字节对齐方式
	cout << sizeof(test_struct) << endl;
	cout << sizeof(test_enum) << endl;
	//注意,这里虽然没有求和,但是也涉及到了计算数据类型边界时候也是字节对齐最大数据类型
	cout << sizeof(test_union) << endl;
	
}

#endif //_TEST_H

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值