C++并没有规定各种数据类型在内存中的存储大小,依赖于不同的编译器的不同而不同,要想获知当前编译器对各种数据类型分配的大小,可以通过sizeof运算符来获取。
使用方法1:
sizeof(数据类型)
使用方法2:
sizeof(变量名 或 常量名 或 表达式 )
sizeof(int)
或
int a;
sizeof(a)
//数据类型空间分配情况
#include <iostream>
using namespace std;
int main()
{
cout<<"vc++6.0 编译环境下,各种数据类型变量所占的内存空间大小(字节为单位)"<<endl;
cout<<"sizeof(int) "<<sizeof(int)<<endl;
cout<<"sizeof(short int) "<<sizeof(short)<<endl;
cout<<"sizeof(long int) "<<sizeof(long)<<endl;
cout<<"sizeof(unsigned int) "<<sizeof(unsigned)<<endl;
cout<<"sizeof(unsigned short int) "<<sizeof(unsigned short)<<endl;
cout<<"sizeof(unsigned long int) "<<sizeof(unsigned long)<<endl;
cout<<"sizeof(char ) "<<sizeof(char)<<endl;
cout<<"sizeof(float) "<<sizeof(float)<<endl;
cout<<"sizeof(double) "<<sizeof(double)<<endl;
cout<<"sizeof(long double) "<<sizeof(long double)<<endl;
return 0;
}
运行结果
本文详细介绍了C++中数据类型在内存中的存储大小如何通过sizeof运算符获取,包括int、short、long、unsigned等基本类型,以及char、float、double等浮点类型。通过实际代码示例展示了在不同编译环境下这些类型的内存空间分配情况。

890

被折叠的 条评论
为什么被折叠?



