纠正下面错误的结构对齐。
typedef struct{
char *string; // 4 byte (type of address int)
char temp; // 1 byte
short pick; // 2 byte
char temp2; // 1 byte
}hello;
- 字符串 = 4
- 临时 + 选择 + temp2(偏移量 7)= 1+2+1
给出答案,良好的对齐是
char *string; // 4 byte (type of address int)
short pick; // 2 byte
char temp; // 1 byte
char temp2; // 1 byte
- 字符串 = 4
- 选择 + temp + temp2(偏移量 7)= 2+1+1
无法理解 temp2 应该位于偏移量 7 而不是 8 的原因。怎么办?请帮忙
最佳答案
+---+---+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
+---+---+---+---+---+---+---+---+
| string | pick | t1| t2|
+---+---+---+---+---+---+---+---+
使用 t1
表示 temp
,使用 t2
表示 temp2
,这是修改后的布局。 t2
的偏移量为 7。
对于 n 字节数量按 n 字节对齐的系统上的原始结构,布局将是:
+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B |
+---+---+---+---+---+---+---+---+---+---+---+---+
| string | t1|pad| pick | t2|pad|pad|pad|
+---+---+---+---+---+---+---+---+---+---+---+---+
这是因为4字节指针需要4字节对齐,所以该结构体的数组需要每个成员都是4字节的倍数。
因此,在原始结构中,t2 的偏移量将为 8,而不是 7。
关于c - 改进 32 位机器上结构的内存对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19486517/