MVC 中奇怪的 sizeof 结果(对齐?)
strange sizeof result in MVC (alignment?)
下面的代码给出了结果
sizeof(t1)=16 sizeof(t2)=16
我本来期望 sizeof(t2)=12 因为 sizeof(fpos_t)=8 和 sizeof(int)=4。有人可以解释一下吗?
int main()
{
typedef struct {
fpos_t fpos;
char* s;
int a;
} t1;
typedef struct {
fpos_t fpos;
int a;
} t2;
t1 it1;
t2 it2;
printf("sizeof(t1)=%d sizeof(t2)=%d ", sizeof(t1), sizeof(t2));
return 0;
}
对于alignment reasons,编译器可以自由插入填充。这意味着结构的大小不一定等于各个成员的大小之和。这是 C 标准明确允许的。
结构开头唯一不允许填充的地方,即第一个成员之前。
Within a structure object, the non-bit-field members and the units in
which bit-fields reside have addresses that increase in the order in
which they are declared. A pointer to a structure object, suitably
converted, points to its initial member (or if that member is a
bit-field, then to the unit in which it resides), and vice versa.
There may be unnamed padding within a structure object, but not at its
beginning.
(强调我的)。
现在大多数计算机一次只允许分配 "words"(又名 8 字节,又名 64 位)。这叫做填充。
把它想象成酒店房间。无论您是 1 人还是 2 人 (chars
) 入住同一个房间 (memory location
),房间的大小都是一样的。
下面的代码给出了结果 sizeof(t1)=16 sizeof(t2)=16 我本来期望 sizeof(t2)=12 因为 sizeof(fpos_t)=8 和 sizeof(int)=4。有人可以解释一下吗?
int main()
{
typedef struct {
fpos_t fpos;
char* s;
int a;
} t1;
typedef struct {
fpos_t fpos;
int a;
} t2;
t1 it1;
t2 it2;
printf("sizeof(t1)=%d sizeof(t2)=%d ", sizeof(t1), sizeof(t2));
return 0;
}
对于alignment reasons,编译器可以自由插入填充。这意味着结构的大小不一定等于各个成员的大小之和。这是 C 标准明确允许的。
结构开头唯一不允许填充的地方,即第一个成员之前。
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
(强调我的)。
现在大多数计算机一次只允许分配 "words"(又名 8 字节,又名 64 位)。这叫做填充。
把它想象成酒店房间。无论您是 1 人还是 2 人 (chars
) 入住同一个房间 (memory location
),房间的大小都是一样的。