2012-09-25 19 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个字节的倍数。