【发布时间】:2010-07-07 09:34:50
【问题描述】:
C 结构中的松弛字节是什么意思?
【问题讨论】:
C 结构中的松弛字节是什么意思?
【问题讨论】:
通常填充字节以确保数据正确对齐。例如:
struct x {
int a; // four bytes
char b; // one byte
// three bytes slack
int c; // four bytes
} xx;
b 和 c 之间可能会有松弛字节,以使 c 在正确的边界上对齐。
您可以通过查看 sizeif(xx) 为您提供的内容来检查这一点(在上述情况下为 12,尽管这取决于实现)。
如果某些架构必须使用(例如)未在四字节边界上对齐的四字节值,则它们的运行速度会变慢。 一些架构根本不允许这样做,而是生成异常。
【讨论】:
struct student
{
char a;//it takes 8 byte
char b;
char c;
char d;
int e;
};
struct student1;
{
char a;
int b;
char c;//it takes 12 byte(suppose sizeof(int)=4;
}
学生被视为:
____________________
|char|char|char|char| // one byte for each char so there is no slack=4byte
|____|____|____|____|
____________________
|int | * | * |* | // int takes for byte;=4byte total space is 4+4=8;
|____|____|____|____|
student1 被视为:
____________________
|char| s |s | s | // one byte for char
|____|____|____|____| // s indicates a slack byte..=4byte
____________________
|int |* |* |* | //int takes four bytes;=4byte
|____|____|____|____|
___________________
|char| s |s | s | // one byte for char
|____|____|____|____| // s indicates a slack byte..=4byte
【讨论】: