字節對齊原則


這個問題也是困擾了我很久的一個問題:

為了加快數據存取的速度,編譯器默認情況下會對結構體成員和結構體本身存儲位置進行處理,使其存放的起始地址是一定字節數的倍數,而不是順序存放,稱為字節對齊.

設對齊字節數為n(n = 1,2,4,8,16),每個成員內存長度為Li,Max(Li)為最大的成員內存長度,字節對齊規則是:

1.       結構體對象的起始地址能夠被Max(Li)所整除;

2.       結構體中每個成員相對於起始地址的偏移量,即對齊值應是min(n,Li)的倍數.若不滿足對齊值的要求,編譯器會在成員之間填充若干個字節;

3.       結構體的總長度值應是min(n,Max)(Li)的倍數,若不滿足總長度值的要求,編譯器在為最后一個成員分配空間后,會在其后填充若干個字節.

(VC默認的對齊字節數n=8)

開不懂,請看下面例子:

 

#include <iostream>
using namespace std;
// 1加1+編譯器補充的2個再加上int 的4個(編譯器自動加的)
typedef struct node1  // 1+1+(2)+4 = 8
{
    char c1;
    char c2;
    int a;
}str1 ;
typedef struct str2 // 1+(3)+4+1+(3) = 12
{
    char c1;
    int a;
    char c2;
}str2 ;
typedef struct str3 // 5+(3)+4+2+(2) = 16
{
    char c1[5];
    int b;
    short c;
}str3 ;
typedef struct str4  // 5+(1)+(2)+4 = 12
{
    char c1[5];
    short c;
    int b;
}str4 ;
typedef struct str5 // 1+1+(6)+8 = 16
{
    char c1;
    char c2;
    double a;
}str5 ;
typedef struct str6 // 1+(7)+8+1+(7) = 24
{
    char c1;
    double a;
    char c2;

}str6 ;
typedef struct str7
{
    char c1;
    str1 s; // 相當於吧str1的結構放在這 char,char,int
    double b;
}str7 ; // 1+1+1+(1)+4+4 = 12

int main()
{
    str1 s1;
    str2 s2;
    str3 s3;
    str4 s4;
    str5 s5;
    str5 s6;
    str7 s7;
    str8 s8;
    cout << "s1 = " << sizeof(s1)<<endl;
    cout << "s2 = " << sizeof(s2)<<endl;
    cout << "s3 = " << sizeof(s3)<<endl;
    cout << "s4 = " << sizeof(s4)<<endl;
    cout << "s5 = " << sizeof(s5)<<endl;
    cout << "s6 = " << sizeof(s6)<<endl;
    cout << "s7 = " << sizeof(s7)<<endl;
    cout << "s8 = " << sizeof(s8)<<endl;
    return 0;
}

 

圖解:

str1

 

str2:

 

 

 str3:

 

 

str4:

 

 str5:

 

 

str6:

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM