2017-05-07 21 views
0

我想知道下面的程序的行爲,因爲填充基於C編程中的相鄰數據類型工作。程序爲什麼填充基於數據類型

[email protected]:~$./mem 
Size of X = 8 
Size of Y = 16 

#include <stdio.h> 
struct abc{ 
    char a1; 
    int a2; 
}X; 
struct efg 
{ 
    char b1; 
    double b2; 
}Y; 
int main() 
{ 
    printf("Size of X = %d\n",sizeof(X)); 
    printf("Size of Y = %d\n",sizeof(Y)); 
    return 0; 
} 

輸出在結構ABC 3個字節被填充,而在結構EFG 7個字節被填充。

這是如何設計的填充?

+1

爲了對齊目的,添加了填充。也許你應該先看看那個方向。 – DeiDei

+0

是的,填充是爲了調整,7字節對齊是不可接受的吧? –

+0

7字節填充僅用於對齊內存。 –

回答

2

正在添加填充以避免成員在不需要時跨越字邊界;正如一些人在評論中所說的那樣。有一個關於它一個很好的解釋在這裏:

http://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/

最大元件的尺寸確實能對其他成員的填充效果。通常,所有成員都與最大成員的大小相匹配。我相信這是因爲它是編譯器確保所有結構成員正確對齊的最簡單/最有效的方式。

因此,一個有趣的細節是,如果您按大小訂購結構成員,並且首先聲明最大的成員,則可以節省空間。下面是一些代碼來說明(我總是覺得看實際內存的轉儲,這樣的事情會有所幫助,而不僅僅是大小)

#include <stdio.h> 

// Inefficient ordering-- to avoid members unnecessarily crossing word 
// boundaries, extra padding is inserted. 
struct X { 
    unsigned long a; // 8 bytes 
    unsigned char b; // 4 bytes 
    unsigned int c; // 4 bytes 
    unsigned char d; // 4 bytes 
}; 

// By ordering the struct this way, we use the space more 
// efficiently. The last two bytes can get packed into a single word. 
struct Y { 
    unsigned long a; // 8 bytes 
    unsigned int c; // 4 bytes 
    unsigned char b; // 1 byte 
    unsigned char d; // 3 bytes 
}; 

struct X x = {.a = 1, .b = 2, .c = 3, .d = 4}; 
struct Y y = {.a = 1, .b = 2, .c = 3, .d = 4}; 

// Print out the data at some memory location, in hex 
void print_mem (void *ptr, unsigned int num) 
{ 
    int i; 
    unsigned char *bptr = (unsigned char *)ptr; 

    for (i = 0; i < num; ++i) { 
     printf("%.2X ", bptr[i]); 
    } 

    printf("\n"); 
} 

int main (void) 
{ 
    print_mem(&x, sizeof(struct X)); // This one will be larger 
    print_mem(&y, sizeof(struct Y)); // This one will be smaller 
    return 0; 
} 

而且運行上面的代碼的輸出:

01 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 00 00 00 00 
01 00 00 00 00 00 00 00 03 00 00 00 02 04 00 00 

這有很多細微之處,我敢肯定它在各種實現上有點不同。請參閱http://www.catb.org/esr/structure-packing瞭解有關結構排序/包裝的更詳細信息...