C++ - 运算符之 sizeof 运算符(概述、基本使用、特殊使用、sizeof 特性、注意事项)

概述

  • sizeof 是 C++ 中的一个重要运算符,用于查询对象或类型的大小(以字节为单位)

一、基本使用

  1. 查询数据类型的大小
#include <iostream>

using namespace std;

int main() {

	cout << "int 大小:" << sizeof(int) << " 字节" << endl;
	cout << "double 大小:" << sizeof(double) << " 字节" << endl;

	return 0;
}
# 输出结果

int 大小:4 字节
double 大小:8 字节
  1. 查询变量的大小
#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 字节

二、特殊使用

  1. 查询数组的大小
#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
  1. 查询结构体和类的大小
#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 字节
  1. 查询指针的大小
#include <iostream>

using namespace std;

int main() {

	int* ptr;
	cout << "指针大小:" << sizeof(ptr) << " 字节" << endl;

	return 0;
}
# 输出结果

指针大小:8 字节

三、sizeof 特性

1、基本介绍
  1. sizeof 返回 size_t 类型,size_t 是无符号整数类型,保证能表示任何对象的大小

  2. sizeof 在编译期间就确定结果,不会产生运行时开销

  3. sizeof 不会计算其操作数的值

2、演示
  1. 返回类型
#include <iostream>

using namespace std;

int main() {

	int arr[10];
	size_t arr_size = sizeof(arr);
	cout << arr_size << endl;

	return 0;
}
# 输出结果

40
  1. 编译时运算
int arr[10];
size_t arr_size = sizeof(arr);

// 等价于直接写(假设 int 占 4 字节)
size_t arr_size = 40;
  1. 不求值
#include <iostream>

using namespace std;

int main() {

	int x = 10;
	cout << sizeof(x++) << endl;
	cout << x << endl;

	return 0;
}
# 输出结果

4
10

四、注意事项

  1. 对动态分配的数组使用 sizeof 只会返回指针大小
#include <iostream>

using namespace std;

int main() {

	int* dynArr = new int[10];
	cout << sizeof(dynArr) << endl;

	return 0;
}
# 输出结果

8
  1. 对于字符串指针,返回指针大小
#include <iostream>

using namespace std;

int main() {

	const char* pStr = "Hello World";
	cout << sizeof(pStr) << endl;

	return 0;
}
# 输出结果

8
  1. 对于字符串字面量,包含终止符
#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值