C++中常用变量在内存中所占的字节数分别是多少?(使用函数sizeof()实测一下不就知道了)

关于C++中常用变量在内存中所占的字节数这个问题,其实没有统一的答案。
因为不同的机器、不同的硬件平台、不同的系统都有可能有不同的标准,特别是整型变量,更是如此。

最好的方式就是用函数sizeof()实测一下。

比如博主用于测试自己当下使用的C++环境各种变量在内存中所占的字节数的代码和结果如下:

#include <iostream>
using namespace std;

int main() 
{
    
    
	cout << "char 类型所占内存字节数为: " << sizeof(char) << endl;

	cout << "short 类型所占内存字节数为: " << sizeof(short) << endl;

	cout << "int 类型所占内存字节数为: " << sizeof(int) << endl;

	cout << "long 类型所占内存字节数为: " << sizeof(long) << endl;

	cout << "long long 类型所占内存字节数为: " << sizeof(long long) << endl;

	cout << "float 类型所占内存字节数为: " << sizeof(float) << endl;

	cout << "double 类型所占内存字节数为: " << sizeof(double) << endl;

	cout << "std::string类型所占内存字节数为: " << sizeof(std::string) << endl;

	return 0;
}

运行结果如下图所示:

在这里插入图片描述
所以对于博主当下的C++环境,结果就是:

  • char 类型所占内存字节数为: 1
  • short 类型所占内存字节数为: 2
  • int 类型所占内存字节数为: 4
  • long 类型所占内存字节数为: 4
  • long long 类型所占内存字节数为: 8
  • float 类型所占内存字节数为: 4
  • double 类型所占内存字节数为: 8
  • std::string类型所占内存字节数为: 28

猜你喜欢

转载自blog.csdn.net/wenhao_ir/article/details/125336402