1.基本類型

sizeof運算符返回類型或者數據對象的長度(字節)，

``````  int a=1;
float b=1.0;
double c=1.0;
long d=1;
char e = '1';

cout<<sizeof(a)<<" "<<sizeof(b)<<" "<<sizeof(c)<<" "<<sizeof(d)<<" "<<sizeof(e)<<endl;
cout<<sizeof(int)<<" "<<sizeof(float)<<" "<<sizeof(double)<<" "<<sizeof(long)<<" "<<sizeof(char)<<endl;

``````

``````4 4 8 8 1
4 4 8 8 1

``````

2.靜態數組

``````int arr[3]={1,1,1};
float arr1[3]={1.0,1.0,1.0};
double arr2[3]={1.0,1.0,1.0};
cout<<sizeof(arr)<<" "<<sizeof(arr1)<<" "<<sizeof(arr2)<<endl;
cout<<sizeof(arr[0])<<" "<<sizeof(arr1[1])<<" "<<sizeof(arr2[2])<<endl;

``````

``````12 12 24
4 4 8

``````

3.動態數組

`````` vector<int>arr1(1,0);
vector<int>arr2(2,0);
vector<int>arr3(3,0);
cout<<sizeof(arr1)<<" "<<sizeof(arr2)<<" "<<sizeof(arr3)<<endl;

``````

`````` 24 24 24

``````

• start;
• finish;
• end_of_storage;

vector 通過配置比其所容納的元素所需更多的內存，即先預留足夠空間，避免二次分配，從而提高 vector 的性能。

so，sizeof(vec)其實得到的是三個指針佔用內存。在64bit系統中，一個指針佔用８個字節。

4.結構體

4.2 字節對齊

1.第一個結構體成員的地址偏移量爲0，以後每個成員偏移量都是成員大小或者有效對齊字節數的最小值的整數倍。如有需要編譯器會在成員之間加上填充字節。

2.結構體總大小是有效對齊值的整數倍。如有需要編譯器會在最末一個成員之後加上填充字節。

``````#例1
struct stru
{
int a;
char b;
int c;
}

``````

``````#例2
struct stru
{
char a;
int b;
int c;
}

``````

``````#例3
struct stru
{
int a;
char b;
char c;
}

``````

``````#例4
struct stru
{
char a;
int b;
char c;
}

``````