How do you find out the how many bytes are used for a certain data type in c++?
本问题已经有最佳答案,请猛点这里访问。
我想知道数据类型在C++中有多少字节,但我不确定从哪里开始。我在谷歌上搜索,但找不到任何东西。
我不知道你怎么会错过
在编程语言C和C++中,一元算子SIZEOF用于计算任何数据类型的大小。size of运算符根据char类型的大小生成操作数的大小。
1 | sizeof ( type-name ) |
请参阅此处的"了解更多信息":msdn
以下是来自msdn的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 ) <<" The length of" << szHello <<" is:" << sizeof szHello <<" The size of the pointer is" << getPtrSize( szHello ) << endl; } |
使用sizeof运算符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #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; } |
输出:
1 2 3 4 5 6 7 8 9 | 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