A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 董立正 中级黑马   /  2015-12-3 10:18  /  1445 人查看  /  9 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*

sizeof运算符是一个单目运算符

作用:计算常量、变量、数据类型在内存中占用的字节数

1)用sizeof计算常量在内存中占用的字节数
sizeof(1) //整型int--> 4

sizeof(2.3f) //单精度型float-->4

sizeof(2.3) //双精度型double-->8

sizeof('a') //字符型char--> 常量 4 变量 1


*/

void test(){

    short result2 = 1;
    int result = 1;
    long result3 = 1;
    float f1 = 2.3f;
    double d1 = 2.3;
    char ch = 'a';
    result = sizeof(1); // short常量 4
    printf("result = %d\n",result);
    result = sizeof(1); // int常量 4
    printf("result = %d\n",result);
    result = sizeof(1); // long常量 4
    printf("result = %d\n",result);
    result = sizeof(2.3f); // float常量 4
    printf("result = %d\n",result);
    result = sizeof(2.3); // double常量 8
    printf("result = %d\n",result);
    //char 占用1个字节, -128~127
    //char 类型的常量存储,97以int类型的数据进行存储  4个字节
    //char 类型的变量存储,把字符型的ascii码转换为二进制(1给字节)进行存储 1个字节
    result = sizeof('a'); // char常量 4
    printf("result = %d\n",result);


}

// 2)sizeof计算变量在内存中占用的字节数

void test2(){

    short result2 = 1;
    int result = 1;
    long result3 = 1;
    float f1 = 2.3f;
    double d1 = 2.3;
    char ch = 'a';
    result = sizeof(result2); // short变量 2
    printf("result = %d\n",result);
    result = sizeof(result); // int变量 4
    printf("result = %d\n",result);
    result = sizeof(result3); // long变量 8
    printf("result = %d\n",result);
    result = sizeof(f1); // float变量 4
    printf("result = %d\n",result);
    result = sizeof(d1); // double变量 8
    printf("result = %d\n",result);
    //char 占用1个字节, -128~127
    //char 类型的常量存储,97以int类型的数据进行存储  4个字节
    //char 类型的变量存储,把字符型的ascii码转换为二进制(1给字节)进行存储 1个字节
    result = sizeof(ch); // char变量 1
    printf("result = %d\n",result);

}


// 3) sizeof计算数据类型在内存中占用的字节数

#include <stdio.h>

int main(int argc, const char * argv[]) {
   
    short result2 = 1;
    int result = 1;
    long result3 = 1;
    float f1 = 2.3f;
    double d1 = 2.3;
    char ch = 'a';
    result = sizeof(short); // short类型 2
    printf("result = %d\n",result);
    result = sizeof(int); // int类型 4
    printf("result = %d\n",result);
    result = sizeof(long); // long类型 8
    printf("result = %d\n",result);
    result = sizeof(float); // float类型 4
    printf("result = %d\n",result);
    result = sizeof(double); // double类型 8
    printf("result = %d\n",result);
    //char 占用1个字节, -128~127
    //char 类型的常量存储,97以int类型的数据进行存储  4个字节
    //char 类型的变量存储,把字符型的ascii码转换为二进制(1给字节)进行存储 1个字节
    result = sizeof(char); // char类型 1
    printf("result = %d\n",result);
    return 0;
}

9 个回复

倒序浏览
谢谢 分享
回复 使用道具 举报

nothing   
回复 使用道具 举报
写的很好~~~
回复 使用道具 举报
zhuwenjia 来自手机 中级黑马 2015-12-4 22:24:08
报纸
谢谢分享
回复 使用道具 举报
记性不好还好有你谢谢分享
回复 使用道具 举报
感谢分享
回复 使用道具 举报
好吧,这样也行...
回复 使用道具 举报
今天刚学到 谢谢分享
回复 使用道具 举报
赞赞赞,谢谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马