C++ 常用数据类型所占空间大小

一、常用数据类型

1、预定义类型,包含整型、字符型、布尔型、浮点型、空类型,指针类型;

2、自定义数据类型,包含数组、结构体struct、联合体union、枚举enum。

二、预定义类型

1.数据类型所占空间

在Linux 64-bit 下,long为8个Bytes。

在64-bit 操作系统中,指针大小为8个Bytes。因为64-bit 操作系统的虚拟内存大小为2^{64}字节,8个Bytes所能表示的最大的数是2^{64},可以实现一一对应关系。

为什么指针类型大小为8个Bytes,却与虚拟内存一一对应,个人理解就是8个Bytes可以用来表示虚拟内存的每一个地址,但不代表所有虚拟内存都被使用。

// windows 64-bit
include <iostream>
using namespace;

int main()
{
    cout<<"sizeof(short)="<<sizeof(short)<<endl;            //sizeof(short)=2
    cout<<"sizeof(int)="<<sizeof(int)<<endl;                //sizeof(int)=4
    cout<<"sizeof(long)="<<sizeof(long)<<endl;              //sizeof(long)=4       
    cout<<"sizeof(long long)="<<sizeof(long long)<<endl;    //sizeof(long long)=8

    cout<<"sizeof(float)="<<sizeof(float)<<endl;                  //sizeof(float)=4
    cout<<"sizeof(double)="<<sizeof(double)<<endl;                //sizeof(double)=8
    cout<<"sizeof(long double)="<<sizeof(long double)<<endl;      //sizeof(long double)=16

    cout<<"sizeof(bool)="<<sizeof(bool)<<endl;      //sizeof(bool)=1
    cout<<"sizeof(char)="<<sizeof(char)<<endl;      //sizeof(char)=1
    cout<<"sizeof(NULL)="<<sizeof(NULL)<<endl;      //sizeof(NULL)=8

    cout<<"sizeof(void*)="<<sizeof(void*)<<endl;      //sizeof(void*)=8
    cout<<"sizeof(int*)="<<sizeof(int*)<<endl;        //sizeof(int*)=8
    cout<<"sizeof(char*)="<<sizeof(char*)<<endl;      //sizeof(char*)=8
    return 0;
}

 

三、自定义数据类型

自定义数据类型,包含数组、结构体struct、联合体union、枚举enum。

1.自定义数据类型

#include<iostream>
using namespace std;

int main()
{   
    int a[3]={1,2,3};

    //结构体数组
    struct Info{
        int age;
        char name[32];
        }info[3];

    //union可以存放多种数据类型,地址会覆盖,可以用来判断大小端
    //struct与int型数据存放地址相同,对z初始化相当于对box里第一个地址初始化
    union myunion{
        struct box
        {
            int x;
            int y;
        }b;
        int z=3;
    }m;

    enum color { red, green=5, blue } c;

    cout<<"sizeof(a)="<<sizeof(a)<<endl;            //sizeof(a)=4*3=12
    cout<<"sizeof(info)="<<sizeof(info)<<endl;      //sizeof(info)=(4+32)*3=108
    cout<<"sizeof(m)="<<sizeof(m)<<endl;            //sizeof(m)=4+4=8  取最大的
    cout<<"sizeof(c)="<<sizeof(c)<<endl;            //sizeof(c)=4   枚举变量的大小,实质是常数所占内存空间的大小
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值