
C++
sizeof(type)
其中,type可以是各种数据类型或变量名,返回值为该数据类型或变量所占用的字节数。例如:
C++
int a;
cout << sizeof(a) << endl; // 输出4,即int类型占用4个字节
char s[] = "Hello";
cout << sizeof(s) << endl; // 输出6,即包括末尾的'\0'共占用6个字节
struct Person {
string name;
int age;
} p;
cout << sizeof(p) << endl; // 输出12,即string类型和int类型分别占用6个字节,共占用12个字节
enum Week { Mon, Tue, Wed, Thu, Fri, Sat, Sun };
cout << sizeof(Week) << endl; // 输出4,即枚举类型默认占用4个字节
需要注意的是,sizeof并不是函数,而是运算符,因此不需要在括号内加上参数的调用方式。同时,sizeof操作的结果是在编译时确定的,而不是在运行时计算得出的。
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号