码迷,mamicode.com
首页 > 其他好文 > 详细

使用sizeof计算大小

时间:2015-05-29 18:00:30      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{
   
    //用 sizeof 计算各类种常量的字节长度
    cout<<"sizeof(‘$‘)="<<sizeof($)<<endl;
    cout<<"sizeof(1)="<<sizeof(1)<<endl;
    cout<<"sizeof(1.5)="<<sizeof(1.5)<<endl;
    cout<<"sizeof(\"Good!\")="<<sizeof("Good!")<<endl;

    //用sizeof 计算各类型变量的字节长度
    int i=100;
    char c=A;
    float x=3.1416; 
    double p=0.1;
    cout<<"sizeof(i)="<<sizeof(i)<<endl;
    cout<<"sizeof(c)="<<sizeof(c)<<endl;
    cout<<"sizeof(x)="<<sizeof(x)<<endl;
    cout<<"sizeof(p)="<<sizeof(p)<<endl;

    //用sizeof 计算表达式的字节长度
    cout<<"sizeof(x+1.732)="<<sizeof(x+1.732)<<endl;

    //用 sizeof 计算各类型的字节长度
    cout<<"sizeof(char)="<<sizeof(char)<<endl;
    cout<<"sizeof(int)="<<sizeof(int)<<endl;
    cout<<"sizeof(float)="<<sizeof(float)<<endl;
    cout<<"sizeof(double)="<<sizeof(double)<<endl;

    //用sizeof 计算数组的字节长度
    char str[]="This is a test.";
    int a[10];    
    double xy[10];
    cout<<"sizeof(str)="<<sizeof(str)<<endl;
    cout<<"sizeof(a)="<<sizeof(a)<<endl;
    cout<<"sizeof(xy)="<<sizeof(xy)<<endl;

    //用sizeof 计算自定义类型的长度
    struct st {
        short num;
        float math_grade;
        float Chinese_grade;
        float sum_grade;
    };
    st student1;
    cout<<"sizeof(st)="<<sizeof(st)<<endl;
    cout<<"sizeof(student1)="<<sizeof(student1)<<endl;
    system("pause");
}

输出结果为:

sizeof($)=1
sizeof(1)=4
sizeof(1.5)=8
sizeof("Good!")=6
sizeof(i)=4
sizeof(c)=1
sizeof(x)=4
sizeof(p)=8
sizeof(x+1.732)=8
sizeof(char)=1
sizeof(int)=4
sizeof(float)=4
sizeof(double)=8
sizeof(str)=16
sizeof(a)=40
sizeof(xy)=80
sizeof(st)=16
sizeof(student1)=16
请按任意键继续. . .

 

使用sizeof计算大小

标签:

原文地址:http://www.cnblogs.com/zhuyaguang/p/4538747.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!