我想知道数据类型在c ++中保存了多少字节,但我不知道从哪里开始。我在谷歌搜索但找不到任何东西。
答案 0 :(得分:2)
我不知道你错过sizeof
的方式。
在编程语言C和C ++中,一元运算符sizeof用于计算任何数据类型的大小。 sizeof运算符根据char类型的大小生成其操作数的大小。
sizeof ( type-name )
请参阅此处了解详情:MSDN
以下是来自MSDN的示例:
size_t getPtrSize( char *ptr )
{
return sizeof( ptr );
}
using namespace std;
int main()
{
char szHello[] = "Hello, world!";
cout << "The size of a char is: "
<< sizeof( char )
<< "\nThe length of " << szHello << " is: "
<< sizeof szHello
<< "\nThe size of the pointer is "
<< getPtrSize( szHello ) << endl;
}
答案 1 :(得分:1)
使用sizeof运算符
#include <iostream>
using namespace std;
int main()
{
cout << "bool:\t\t" << sizeof(bool) << " bytes" << endl;
cout << "char:\t\t" << sizeof(char) << " bytes" << endl;
cout << "wchar_t:\t" << sizeof(wchar_t) << " bytes" << endl;
cout << "short:\t\t" << sizeof(short) << " bytes" << endl;
cout << "int:\t\t" << sizeof(int) << " bytes" << endl;
cout << "long:\t\t" << sizeof(long) << " bytes" << endl;
cout << "float:\t\t" << sizeof(float) << " bytes" << endl;
cout << "double:\t\t" << sizeof(double) << " bytes" << endl;
cout << "long double:\t" << sizeof(long double) << " bytes" << endl;
return 0;
}
输出:
bool: 1 bytes
char: 1 bytes
wchar_t: 2 bytes
short: 2 bytes
int: 4 bytes
long: 4 bytes
float: 4 bytes
double: 8 bytes
long double: 12 bytes
使用MinGW g ++ 4.7.2 Windows