该程序使用指针(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来确定每个结构成员的填充。 –