C/C++ 数据类型
不同数据类型具体的长度(字节数)受采用的编译器和编译环境影响,采用不同的编译器在一些数据类型上会得到不同的结果,比较容易有不同的数据类型有 int, long. 本文使用的编译器为 gcc,所使用的系统是 linux64.
1. int, char, short, long
#include<iostream>
#include<string>
using namespace std;
int main(){
int a;
short b;
long c;
char d;
cout << sizeof(a) << endl; //运行结果:4
cout << sizeof(b) << endl; //运行结果:2
cout << sizeof(c) << endl; //运行结果:8
cout << sizeof(d) << endl; //运行结果:1
}
看到很多别人博客中 long
类型的长度为4 bytes,这里附上一张图:
2. 指针类型:char*, int*
指针类型的字节数取决于操作系统的位数。32-bit 系统中指针的长度为32 bits(4 bytes),64-bit 系统中指针的长度为64 bits(8 bytes)。
#include<iostream>
#include<string>
using namespace std;
int main(){
int* a;
char* b;
cout << sizeof(a) << endl; // 运行结果:8
cout << sizeof(b) << endl; // 运行结果:8
}
reference:不同类型变量长度的图片源于:https://app.assembla.com/spaces/zsync-windows/wiki/Types_sizes