该程序使用指针(8 个字节)和 3 个整数(每个 4 个字节)创建和测量一个结构,并显示有 4 个字节的数据填充。
我不明白为什么有 4 个字节的数据填充,或者 CPU 一次处理 8 个字节,应该还有另外 8 个字节的填充,或者它一次处理 4 个字节,应该没有对吗?
还是将 2 个 4 字节的值粘贴在 8 字节的内存部分中,并让 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