C++中关键字sizeof如何简单使用

2025-11-20 07:50:58

1、基本格式

sizeof(变量);

sizeof(类型);

sizeof  对象;  

C++中关键字sizeof如何简单使用

2、计算字符类型的存储空间,通常为1字节

char c='b';

sizeof(char);

sizeof(c);

C++中关键字sizeof如何简单使用

C++中关键字sizeof如何简单使用

3、计算整型的存储空间,通常为4字节

int c='b';

sizeof(int);

sizeof(c);

C++中关键字sizeof如何简单使用

C++中关键字sizeof如何简单使用

4、计算数组的sizeof,主要与元素个数有关。内存大小=元素个数*类型存储空间:

 int c[]={1,2 ,3,4};

 cout<<sizeof(c)<<endl;

 cout<<sizeof(c)/sizeof(c[0]);//可用于计算数组大小

C++中关键字sizeof如何简单使用

C++中关键字sizeof如何简单使用

5、计算结构体的sizeof,由于字节需要对齐。内存空间=成员个数*最大类型空间

#include <iostream>

using namespace std;

struct inte

{

      int a;

      double n;

};

int main()

{

cout<<sizeof(inte)<<endl;

return 0;

}

C++中关键字sizeof如何简单使用

C++中关键字sizeof如何简单使用

6、类的sizeof计算,与结构体类似

#include <iostream>

using namespace std;

class inte

{

      int a;

      double n;

      int serach(){return 1;}

};

int main()

{

cout<<sizeof(inte)<<endl;

return 0;

}

C++中关键字sizeof如何简单使用

C++中关键字sizeof如何简单使用

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢