概述
- sizeof 是 C++ 中的一个重要运算符,用于查询对象或类型的大小(以字节为单位)
一、基本使用
- 查询数据类型的大小
#include <iostream>
using namespace std;
int main() {
cout << "int 大小:" << sizeof(int) << " 字节" << endl;
cout << "double 大小:" << sizeof(double) << " 字节" << endl;
return 0;
}
# 输出结果
int 大小:4 字节
double 大小:8 字节
- 查询变量的大小
#include <iostream>
using namespace std;
int main() {
int x = 10;
double y = 3.14;
// 等价于 sizeof(int)
cout << "x 大小:" << sizeof(x) << " 字节" << endl;
// 等价于 sizeof(double)
cout << "y 大小:" << sizeof(y) << " 字节" << endl;
return 0;
}
# 输出结果
x 大小:4 字节
y 大小:8 字节
二、特殊使用
- 查询数组的大小
#include <iostream>
using namespace std;
int main() {
int arr[10];
cout << "数组总大小: " << sizeof(arr) << " 字节" << endl;
cout << "数组元素数: " << sizeof(arr) / sizeof(arr[0]) << endl;
return 0;
}
# 输出结果
数组总大小: 40 字节
数组元素数: 10
- 查询结构体和类的大小
#include <iostream>
using namespace std;
struct Point {
double x;
double y;
double r;
};
int main() {
cout << "Point 大小:" << sizeof(Point) << " 字节" << endl;
Point point;
point.x = 1.0;
point.y = 2.0;
point.r = 3.0;
cout << "point 大小:" << sizeof(point) << " 字节" << endl;
return 0;
}
# 输出结果
Point 大小:24 字节
point 大小:24 字节
- 查询指针的大小
#include <iostream>
using namespace std;
int main() {
int* ptr;
cout << "指针大小:" << sizeof(ptr) << " 字节" << endl;
return 0;
}
# 输出结果
指针大小:8 字节
三、sizeof 特性
1、基本介绍
-
sizeof 返回
size_t
类型,size_t
是无符号整数类型,保证能表示任何对象的大小 -
sizeof 在编译期间就确定结果,不会产生运行时开销
-
sizeof 不会计算其操作数的值
2、演示
- 返回类型
#include <iostream>
using namespace std;
int main() {
int arr[10];
size_t arr_size = sizeof(arr);
cout << arr_size << endl;
return 0;
}
# 输出结果
40
- 编译时运算
int arr[10];
size_t arr_size = sizeof(arr);
// 等价于直接写(假设 int 占 4 字节)
size_t arr_size = 40;
- 不求值
#include <iostream>
using namespace std;
int main() {
int x = 10;
cout << sizeof(x++) << endl;
cout << x << endl;
return 0;
}
# 输出结果
4
10
四、注意事项
- 对动态分配的数组使用 sizeof 只会返回指针大小
#include <iostream>
using namespace std;
int main() {
int* dynArr = new int[10];
cout << sizeof(dynArr) << endl;
return 0;
}
# 输出结果
8
- 对于字符串指针,返回指针大小
#include <iostream>
using namespace std;
int main() {
const char* pStr = "Hello World";
cout << sizeof(pStr) << endl;
return 0;
}
# 输出结果
8
- 对于字符串字面量,包含终止符
#include <iostream>
using namespace std;
int main() {
const char str[] = "Hello World";
cout << sizeof(str) << endl;
cout << sizeof("Hello") << endl; // (H,e,l,l,o,\0)
return 0;
}
# 输出结果
12
6