C++ sizeof

sizeof :运算符,返回类型或数据对象的长度,单位为字节。

用法:

  • 数据类型:sizeof(char):返回对应长度。
  • 普通变量:sizeof(a):返回对应长度。
  • 数组:sizeof(数组名):返回整个数组所占字节数。sizeof(数组元素):返回元素长度。
  • 指针:sizeof(p):返回指针长度。本系统均为8字节。
void test_sizeof()
{
    cout << sizeof(char) << endl;  //1
    cout << sizeof(int) << endl;  //4
    cout << sizeof(double) << endl;  //8

    int a = 3;
    int arr[5] = {4, 6};
    int arr2[] = {7, 8, 9};

    cout << sizeof(a) << endl;  //4
    cout << sizeof(arr[1]) << endl; //4
    cout << sizeof(arr) << endl; //20
    cout << sizeof(arr2) << endl; //12

    int *p = arr;
    int *q = &arr[1];

    cout << p << endl;  //0x65fdb0
    cout << *p << endl;  //4
    cout << q << endl;  //0x65fdb4
    cout << *q << endl;  //6

    cout << sizeof(p) << endl;  //8
    cout << sizeof(*p) << endl;  //4
    cout << sizeof(q) << endl;  //8
    cout << sizeof(*q) << endl;  //4

    char *cptr;
    short *sptr;
    int *ptr;
    double *dptr;

    cout << sizeof(cptr) << endl; //8
    cout << sizeof(*cptr) << endl; //1
    cout << sizeof(sptr) << endl; //8
    cout << sizeof(*sptr) << endl; //2
    cout << sizeof(ptr) << endl; //8
    cout << sizeof(*ptr) << endl; //4
    cout << sizeof(dptr) << endl; //8
    cout << sizeof(*dptr) << endl; //8
}
  • 用于字符串char数组:sizeof 返回值与存储内容无关,返回数组大小。
    const int Size = 10;
    char name[Size];
    cin >> name; // fan
    cout << sizeof(name) << endl; //10
    cout << strlen(name) << endl; //3
  • sizeof 指出整个数组的长度:10字节。
  • strlen 返回存储在数组中的字符串的长度,不包含结尾的空字符 '\0' 。
    const int Size = 10;
    char name[Size];
    cin >> name; // 12345678 9
    cout << sizeof(name) << endl; //10
    cout << strlen(name) << endl; //8
    const int Size = 10;
    char name[Size];
    cin >> name; // 123456789101112
    cout << sizeof(name) << endl; //10
    cout << strlen(name) << endl; //15

sizeof 与 strlen 区别:

  • sizeof 是操作符, strlen 是库函数,存放在<cstring>头文件中。
  • sizeof 参数可以是类型或变量,strlen 以字符串为参数,接受char数组。
  • sizeof 在编译时已知,strlen 在运行时计算。
  • sizeof 计算内存大小,与具体内容无关,strlen 计算字符串实际长度,遇到空字符结束,不包含结尾空字符 ‘\0’ 。
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值