該程序使用指針(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
你爲什麼認爲效率低下? – Nim
您可以使用offsetof來確定每個結構成員的填充。 –