英文:
Why memory alignment of structs that contain arrays of type T is always 1
问题
我在探讨内存对齐和填充问题,以为自己已经掌握了,直到遇到这个问题:
```cpp
struct Example {
int x1; // 4
char c; // 1 + 3 填充
int x2; // 4
};
static_assert(sizeof Example == 12, "大小不正确"); // 正确
struct Example2 {
long long x; // 8
Example y; // 12
// 4 字节填充
};
static_assert(sizeof Example2 == 24, "大小不正确"); // 正确
struct Example3 {
unsigned char x[8]; // 8
unsigned char y[12]; // 12
// 4 字节填充??
};
static_assert(sizeof Example3 == 24, "大小不正确"); // 错误
我使用的是 64 位系统,使用 MSVC x64 编译器。为什么它总是将只包含数组类型的结构的内存对齐计算为 1?
<details>
<summary>英文:</summary>
I was exploring memory alignment and padding, and thought that I got the hang of it until I came across this:
```cpp
struct Example {
int x1; // 4
char c; // 1 + 3 padding
int x2; // 4
};
static_assert(sizeof Example == 12, "Incorrect size"); // OK
struct Example2 {
long long x; // 8
Example y; // 12
// 4 bytes padding
};
static_assert(sizeof Example2 == 24, "Incorrect size"); // OK
struct Example3 {
unsigned char x[8]; // 8
unsigned char y[12]; // 12
// 4 bytes padding??
};
static_assert(sizeof Example3 == 24, "Incorrect size"); // ERROR
I am on a 64-bit system, using MSVC x64 compiler. Why does it always calculate memory alignments for structs with only array types as 1?
答案1
得分: 1
long long x;
需要8字节对齐,编译器会添加4字节填充以使Example2
数组中的元素正确对齐。
unsigned char x[8];
不需要任何对齐,Example3
数组中的元素不需要对齐,因此编译器不会添加填充字节,但它可以添加,这取决于具体的实现。
英文:
long long x;
requires the alignment 8, the compiler adds the 4 bytes padding to make elements in an array of Example2
properly aligned.
unsigned char x[8];
doesn't require any alignment, the elements in an array of Example3
do not need to be aligned, thus the compiler doesn't add padding bytes, but it can add them, it's implementation specific.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论