2012-09-25 47 views
0

該程序使用指針(8字節)和3個整數(每個4個字節)創建並測量結構,並顯示有4個字節的數據填充。64位系統差異的數據填充

我不明白爲什麼有4個字節的數據填充,要麼CPU一次處理8個字節,應該有另外8個填充字節,或者一次處理4個字節,應該有沒有權利?

或者是否在內存的8字節部分粘貼了2個4字節的值,並讓CPU在運行時將其分開? (這可以解釋的差異,但好像有點低效我)

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

struct test { 
    char *name; 
    int age; 
    int height; 
    int weight; 
}; 

struct test *create(char *name, int age, int height, int weight) 
{ 
    struct test *thing = malloc(sizeof(struct test)); 

    thing->name = strdup(name); 
    thing->age = age; 
    thing->height = height; 
    thing->weight = weight; 

    return thing; 
} 

void destroy(struct test *thing) 
{ 
    free(thing->name); 
    free(thing); 
} 


int main(int argc, char *argv[]) 
{ 
    struct test * t1 = create("bleh",1,2,3); 

    printf("Sizeof struct: %lu\n",sizeof(struct test)); 
    printf("Sizeof pointer (On 64bit system): %lu\n",sizeof(char *)); 
    printf("Sizeof int: %lu\n",sizeof(int)); 

    destroy(t1); 

    return 0; 
} 

輸出:

Sizeof struct: 24 
Sizeof pointer (On 64bit system): 8 
Sizeof int: 4 
+0

你爲什麼認爲效率低下? – Nim

+0

您可以使用offsetof來確定每個結構成員的填充。 –

回答

3

整個結構可能是填充底,對位的原因。這是必要的,因爲你可能想要有一個這個結構的數組。

你提到的填充使得該結構總是最終上它是由8

+0

我沒想到,謝謝! –

3

指針大概需要在8個字節對齊整除的地址。想想你在組建你的班級時會發生什麼,test a[10]。確保a[i].name在8個字節上對齊的唯一方法是將該類填充爲8個字節的倍數。